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/soap/generator.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/generator.rb
# SOAP4R - SOAP XML Instance Generator 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. require 'xsd/ns' require 'soap/soap' require 'soap/baseData' require 'soap/encodingstyle/handler' module SOAP ### ## CAUTION: MT-unsafe # class SOAPGenerator include SOAP class FormatEncodeError < Error; end public attr_accessor :charset attr_accessor :default_encodingstyle attr_accessor :generate_explicit_type attr_accessor :use_numeric_character_reference def initialize(opt = {}) @reftarget = nil @handlers = {} @charset = opt[:charset] || XSD::Charset.xml_encoding_label @default_encodingstyle = opt[:default_encodingstyle] || EncodingNamespace @generate_explicit_type = opt.key?(:generate_explicit_type) ? opt[:generate_explicit_type] : true @elementformdefault = opt[:elementformdefault] @attributeformdefault = opt[:attributeformdefault] @use_numeric_character_reference = opt[:use_numeric_character_reference] @indentstr = opt[:no_indent] ? '' : ' ' @buf = @indent = @curr = nil end def generate(obj, io = nil) @buf = io || '' @indent = '' prologue @handlers.each do |uri, handler| handler.encode_prologue end ns = XSD::NS.new @buf << xmldecl encode_data(ns, obj, nil) @handlers.each do |uri, handler| handler.encode_epilogue end epilogue @buf end def encode_data(ns, obj, parent) if obj.is_a?(SOAPEnvelopeElement) encode_element(ns, obj, parent) return end if @reftarget && !obj.precedents.empty? add_reftarget(obj.elename.name, obj) ref = SOAPReference.new(obj) ref.elename = ref.elename.dup_name(obj.elename.name) obj.precedents.clear # Avoid cyclic delay. obj.encodingstyle = parent.encodingstyle # SOAPReference is encoded here. obj = ref end encodingstyle = obj.encodingstyle # Children's encodingstyle is derived from its parent. encodingstyle ||= parent.encodingstyle if parent obj.encodingstyle = encodingstyle handler = find_handler(encodingstyle || @default_encodingstyle) unless handler raise FormatEncodeError.new("Unknown encodingStyle: #{ encodingstyle }.") end if !obj.elename.name raise FormatEncodeError.new("Element name not defined: #{ obj }.") end handler.encode_data(self, ns, obj, parent) handler.encode_data_end(self, ns, obj, parent) end def add_reftarget(name, node) unless @reftarget raise FormatEncodeError.new("Reftarget is not defined.") end @reftarget.add(name, node) end def encode_child(ns, child, parent) indent_backup, @indent = @indent, @indent + @indentstr encode_data(ns.clone_ns, child, parent) @indent = indent_backup end def encode_element(ns, obj, parent) attrs = {} if obj.is_a?(SOAPBody) @reftarget = obj obj.encode(self, ns, attrs) do |child| indent_backup, @indent = @indent, @indent + @indentstr encode_data(ns.clone_ns, child, obj) @indent = indent_backup end @reftarget = nil else if obj.is_a?(SOAPEnvelope) # xsi:nil="true" can appear even if dumping without explicit type. SOAPGenerator.assign_ns(attrs, ns, XSD::InstanceNamespace, XSINamespaceTag) if @generate_explicit_type SOAPGenerator.assign_ns(attrs, ns, XSD::Namespace, XSDNamespaceTag) end end obj.encode(self, ns, attrs) do |child| indent_backup, @indent = @indent, @indent + @indentstr encode_data(ns.clone_ns, child, obj) @indent = indent_backup end end end def encode_name(ns, data, attrs) if element_local?(data) data.elename.name else if element_qualified?(data) SOAPGenerator.assign_ns(attrs, ns, data.elename.namespace, '') else SOAPGenerator.assign_ns(attrs, ns, data.elename.namespace) end ns.name(data.elename) end end def encode_name_end(ns, data) if element_local?(data) data.elename.name else ns.name(data.elename) end end def encode_tag(elename, attrs = nil) if !attrs or attrs.empty? @buf << "\n#{ @indent }<#{ elename }>" elsif attrs.size == 1 key, value = attrs.shift @buf << %Q[\n#{ @indent }<#{ elename } #{ key }="#{ value }">] else @buf << "\n#{ @indent }<#{ elename } " << attrs.collect { |key, value| %Q[#{ key }="#{ value }"] }.join("\n#{ @indent }#{ @indentstr * 2 }") << '>' end end def encode_tag_end(elename, cr = nil) if cr @buf << "\n#{ @indent }</#{ elename }>" else @buf << "</#{ elename }>" end end def encode_rawstring(str) @buf << str end EncodeMap = { '&' => '&amp;', '<' => '&lt;', '>' => '&gt;', '"' => '&quot;', '\'' => '&apos;', "\r" => '&#xd;' } EncodeCharRegexp = Regexp.new("[#{EncodeMap.keys.join}]") def encode_string(str) if @use_numeric_character_reference and !XSD::Charset.is_us_ascii(str) str.gsub!(EncodeCharRegexp) { |c| EncodeMap[c] } @buf << str.unpack("U*").collect { |c| if c == 0x9 or c == 0xa or c == 0xd or (c >= 0x20 and c <= 0x7f) c.chr else sprintf("&#x%x;", c) end }.join else @buf << str.gsub(EncodeCharRegexp) { |c| EncodeMap[c] } end end def element_local?(element) element.elename.namespace.nil? end def element_qualified?(element) if element.respond_to?(:qualified) if element.qualified.nil? @elementformdefault else element.qualified end else @elementformdefault end end def self.assign_ns(attrs, ns, namespace, tag = nil) if namespace.nil? raise FormatEncodeError.new("empty namespace") end unless ns.assigned?(namespace) tag = ns.assign(namespace, tag) if tag == '' attr = 'xmlns' else attr = "xmlns:#{tag}" end attrs[attr] = namespace end end private def prologue end def epilogue end def find_handler(encodingstyle) unless @handlers.key?(encodingstyle) handler = SOAP::EncodingStyle::Handler.handler(encodingstyle).new(@charset) handler.generate_explicit_type = @generate_explicit_type handler.encode_prologue @handlers[encodingstyle] = handler end @handlers[encodingstyle] end def xmldecl if @charset %Q[<?xml version="1.0" encoding="#{ @charset }" ?>] else %Q[<?xml version="1.0" ?>] 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/marshal.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/marshal.rb
# SOAP4R - Marshalling/Unmarshalling Ruby's object using SOAP Encoding. # 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 "soap/mapping" require "soap/processor" module SOAP module Marshal # Trying xsd:dateTime data to be recovered as aTime. MarshalMappingRegistry = Mapping::Registry.new( :allow_original_mapping => true) MarshalMappingRegistry.add( Time, ::SOAP::SOAPDateTime, ::SOAP::Mapping::Registry::DateTimeFactory ) class << self public def dump(obj, io = nil) marshal(obj, MarshalMappingRegistry, io) end def load(stream) unmarshal(stream, MarshalMappingRegistry) end def marshal(obj, mapping_registry = MarshalMappingRegistry, io = nil) elename = Mapping.name2elename(obj.class.to_s) soap_obj = Mapping.obj2soap(obj, mapping_registry) body = SOAPBody.new body.add(elename, soap_obj) env = SOAPEnvelope.new(nil, body) SOAP::Processor.marshal(env, {}, io) end def unmarshal(stream, mapping_registry = MarshalMappingRegistry) env = SOAP::Processor.unmarshal(stream) if env.nil? raise ArgumentError.new("Illegal SOAP marshal format.") end Mapping.soap2obj(env.body.root_node, mapping_registry) end end end end SOAPMarshal = SOAP::Marshal
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/baseData.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/baseData.rb
# soap/baseData.rb: SOAP4R - Base type 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/datatypes' require 'soap/soap' module SOAP ### ## Mix-in module for SOAP base type classes. # module SOAPModuleUtils include SOAP public def decode(elename) d = self.new d.elename = elename d end end ### ## for SOAP type(base and compound) # module SOAPType attr_accessor :encodingstyle attr_accessor :elename attr_accessor :id attr_reader :precedents attr_accessor :root attr_accessor :parent attr_accessor :position attr_reader :extraattr attr_accessor :definedtype def initialize(*arg) super @encodingstyle = nil @elename = XSD::QName::EMPTY @id = nil @precedents = [] @root = false @parent = nil @position = nil @definedtype = nil @extraattr = {} end def inspect if self.is_a?(XSD::NSDBase) sprintf("#<%s:0x%x %s %s>", self.class.name, __id__, self.elename, self.type) else sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.elename) end end def rootnode node = self while node = node.parent break if SOAPEnvelope === node end node end end ### ## for SOAP base type # module SOAPBasetype include SOAPType include SOAP def initialize(*arg) super end end ### ## for SOAP compound type # module SOAPCompoundtype include SOAPType include SOAP def initialize(*arg) super end end ### ## Convenience datatypes. # class SOAPReference < XSD::NSDBase include SOAPBasetype extend SOAPModuleUtils public attr_accessor :refid # Override the definition in SOAPBasetype. def initialize(obj = nil) super() @type = XSD::QName::EMPTY @refid = nil @obj = nil __setobj__(obj) if obj end def __getobj__ @obj end def __setobj__(obj) @obj = obj @refid = @obj.id || SOAPReference.create_refid(@obj) @obj.id = @refid unless @obj.id @obj.precedents << self # Copies NSDBase information @obj.type = @type unless @obj.type end # Why don't I use delegate.rb? # -> delegate requires target object type at initialize time. # Why don't I use forwardable.rb? # -> forwardable requires a list of forwarding methods. # # ToDo: Maybe I should use forwardable.rb and give it a methods list like # delegate.rb... # def method_missing(msg_id, *params) if @obj @obj.send(msg_id, *params) else nil end end def refidstr '#' + @refid end def self.create_refid(obj) 'id' + obj.__id__.to_s end def self.decode(elename, refidstr) if /\A#(.*)\z/ =~ refidstr refid = $1 elsif /\Acid:(.*)\z/ =~ refidstr refid = $1 else raise ArgumentError.new("illegal refid #{refidstr}") end d = super(elename) d.refid = refid d end end class SOAPExternalReference < XSD::NSDBase include SOAPBasetype extend SOAPModuleUtils def initialize super() @type = XSD::QName::EMPTY end def referred rootnode.external_content[external_contentid] = self end def refidstr 'cid:' + external_contentid end private def external_contentid raise NotImplementedError.new end end class SOAPNil < XSD::XSDNil include SOAPBasetype extend SOAPModuleUtils end # SOAPRawString is for sending raw string. In contrast to SOAPString, # SOAP4R does not do XML encoding and does not convert its CES. The string it # holds is embedded to XML instance directly as a 'xsd:string'. class SOAPRawString < XSD::XSDString include SOAPBasetype extend SOAPModuleUtils end ### ## Basic datatypes. # class SOAPAnySimpleType < XSD::XSDAnySimpleType include SOAPBasetype extend SOAPModuleUtils end class SOAPString < XSD::XSDString include SOAPBasetype extend SOAPModuleUtils end class SOAPBoolean < XSD::XSDBoolean include SOAPBasetype extend SOAPModuleUtils end class SOAPDecimal < XSD::XSDDecimal include SOAPBasetype extend SOAPModuleUtils end class SOAPFloat < XSD::XSDFloat include SOAPBasetype extend SOAPModuleUtils end class SOAPDouble < XSD::XSDDouble include SOAPBasetype extend SOAPModuleUtils end class SOAPDuration < XSD::XSDDuration include SOAPBasetype extend SOAPModuleUtils end class SOAPDateTime < XSD::XSDDateTime include SOAPBasetype extend SOAPModuleUtils end class SOAPTime < XSD::XSDTime include SOAPBasetype extend SOAPModuleUtils end class SOAPDate < XSD::XSDDate include SOAPBasetype extend SOAPModuleUtils end class SOAPGYearMonth < XSD::XSDGYearMonth include SOAPBasetype extend SOAPModuleUtils end class SOAPGYear < XSD::XSDGYear include SOAPBasetype extend SOAPModuleUtils end class SOAPGMonthDay < XSD::XSDGMonthDay include SOAPBasetype extend SOAPModuleUtils end class SOAPGDay < XSD::XSDGDay include SOAPBasetype extend SOAPModuleUtils end class SOAPGMonth < XSD::XSDGMonth include SOAPBasetype extend SOAPModuleUtils end class SOAPHexBinary < XSD::XSDHexBinary include SOAPBasetype extend SOAPModuleUtils end class SOAPBase64 < XSD::XSDBase64Binary include SOAPBasetype extend SOAPModuleUtils Type = QName.new(EncodingNamespace, Base64Literal) public # Override the definition in SOAPBasetype. def initialize(value = nil) super(value) @type = Type end def as_xsd @type = XSD::XSDBase64Binary::Type end end class SOAPAnyURI < XSD::XSDAnyURI include SOAPBasetype extend SOAPModuleUtils end class SOAPQName < XSD::XSDQName include SOAPBasetype extend SOAPModuleUtils end class SOAPInteger < XSD::XSDInteger include SOAPBasetype extend SOAPModuleUtils end class SOAPNonPositiveInteger < XSD::XSDNonPositiveInteger include SOAPBasetype extend SOAPModuleUtils end class SOAPNegativeInteger < XSD::XSDNegativeInteger include SOAPBasetype extend SOAPModuleUtils end class SOAPLong < XSD::XSDLong include SOAPBasetype extend SOAPModuleUtils end class SOAPInt < XSD::XSDInt include SOAPBasetype extend SOAPModuleUtils end class SOAPShort < XSD::XSDShort include SOAPBasetype extend SOAPModuleUtils end class SOAPByte < XSD::XSDByte include SOAPBasetype extend SOAPModuleUtils end class SOAPNonNegativeInteger < XSD::XSDNonNegativeInteger include SOAPBasetype extend SOAPModuleUtils end class SOAPUnsignedLong < XSD::XSDUnsignedLong include SOAPBasetype extend SOAPModuleUtils end class SOAPUnsignedInt < XSD::XSDUnsignedInt include SOAPBasetype extend SOAPModuleUtils end class SOAPUnsignedShort < XSD::XSDUnsignedShort include SOAPBasetype extend SOAPModuleUtils end class SOAPUnsignedByte < XSD::XSDUnsignedByte include SOAPBasetype extend SOAPModuleUtils end class SOAPPositiveInteger < XSD::XSDPositiveInteger include SOAPBasetype extend SOAPModuleUtils end ### ## Compound datatypes. # class SOAPStruct < XSD::NSDBase include SOAPCompoundtype include Enumerable public def initialize(type = nil) super() @type = type || XSD::QName::EMPTY @array = [] @data = [] end def to_s() str = '' self.each do |key, data| str << "#{key}: #{data}\n" end str end def add(name, value) add_member(name, value) end def [](idx) if idx.is_a?(Range) @data[idx] elsif idx.is_a?(Integer) if (idx > @array.size) raise ArrayIndexOutOfBoundsError.new('In ' << @type.name) end @data[idx] else if @array.include?(idx) @data[@array.index(idx)] else nil end end end def []=(idx, data) if @array.include?(idx) data.parent = self if data.respond_to?(:parent=) @data[@array.index(idx)] = data else add(idx, data) end end def key?(name) @array.include?(name) end def members @array end def to_obj hash = {} proptype = {} each do |k, v| value = v.respond_to?(:to_obj) ? v.to_obj : v.to_s case proptype[k] when :single hash[k] = [hash[k], value] proptype[k] = :multi when :multi hash[k] << value else hash[k] = value proptype[k] = :single end end hash end def each idx = 0 while idx < @array.length yield(@array[idx], @data[idx]) idx += 1 end end def replace members.each do |member| self[member] = yield(self[member]) end end def self.decode(elename, type) s = SOAPStruct.new(type) s.elename = elename s end private def add_member(name, value = nil) value = SOAPNil.new() if value.nil? @array.push(name) value.elename = value.elename.dup_name(name) @data.push(value) value.parent = self if value.respond_to?(:parent=) value end end # SOAPElement is not typed so it is not derived from NSDBase. class SOAPElement include Enumerable attr_accessor :encodingstyle attr_accessor :elename attr_accessor :id attr_reader :precedents attr_accessor :root attr_accessor :parent attr_accessor :position attr_accessor :extraattr attr_accessor :qualified def initialize(elename, text = nil) if !elename.is_a?(XSD::QName) elename = XSD::QName.new(nil, elename) end @encodingstyle = LiteralNamespace @elename = elename @id = nil @precedents = [] @root = false @parent = nil @position = nil @extraattr = {} @qualified = nil @array = [] @data = [] @text = text end def inspect sprintf("#<%s:0x%x %s>", self.class.name, __id__, self.elename) end # Text interface. attr_accessor :text alias data text # Element interfaces. def add(value) add_member(value.elename.name, value) end def [](idx) if @array.include?(idx) @data[@array.index(idx)] else nil end end def []=(idx, data) if @array.include?(idx) data.parent = self if data.respond_to?(:parent=) @data[@array.index(idx)] = data else add(data) end end def key?(name) @array.include?(name) end def members @array end def to_obj if members.empty? @text else hash = {} proptype = {} each do |k, v| value = v.respond_to?(:to_obj) ? v.to_obj : v.to_s case proptype[k] when :single hash[k] = [hash[k], value] proptype[k] = :multi when :multi hash[k] << value else hash[k] = value proptype[k] = :single end end hash end end def each idx = 0 while idx < @array.length yield(@array[idx], @data[idx]) idx += 1 end end def self.decode(elename) o = SOAPElement.new(elename) o end def self.from_obj(obj, namespace = nil) o = SOAPElement.new(nil) case obj when nil o.text = nil when Hash obj.each do |elename, value| if value.is_a?(Array) value.each do |subvalue| child = from_obj(subvalue, namespace) child.elename = to_elename(elename, namespace) o.add(child) end else child = from_obj(value, namespace) child.elename = to_elename(elename, namespace) o.add(child) end end else o.text = obj.to_s end o end def self.to_elename(obj, namespace = nil) if obj.is_a?(XSD::QName) obj elsif /\A(.+):([^:]+)\z/ =~ obj.to_s XSD::QName.new($1, $2) else XSD::QName.new(namespace, obj.to_s) end end private def add_member(name, value) add_accessor(name) @array.push(name) @data.push(value) value.parent = self if value.respond_to?(:parent=) value end if RUBY_VERSION > "1.7.0" def add_accessor(name) methodname = name if self.respond_to?(methodname) methodname = safe_accessor_name(methodname) end Mapping.define_singleton_method(self, methodname) do @data[@array.index(name)] end Mapping.define_singleton_method(self, methodname + '=') do |value| @data[@array.index(name)] = value end end else def add_accessor(name) methodname = safe_accessor_name(name) instance_eval <<-EOS def #{methodname} @data[@array.index(#{name.dump})] end def #{methodname}=(value) @data[@array.index(#{name.dump})] = value end EOS end end def safe_accessor_name(name) "var_" << name.gsub(/[^a-zA-Z0-9_]/, '') end end class SOAPArray < XSD::NSDBase include SOAPCompoundtype include Enumerable public attr_accessor :sparse attr_reader :offset, :rank attr_accessor :size, :size_fixed attr_reader :arytype def initialize(type = nil, rank = 1, arytype = nil) super() @type = type || ValueArrayName @rank = rank @data = Array.new @sparse = false @offset = Array.new(rank, 0) @size = Array.new(rank, 0) @size_fixed = false @position = nil @arytype = arytype end def offset=(var) @offset = var @sparse = true end def add(value) self[*(@offset)] = value end def [](*idxary) if idxary.size != @rank raise ArgumentError.new("given #{idxary.size} params does not match rank: #{@rank}") end retrieve(idxary) end def []=(*idxary) value = idxary.slice!(-1) if idxary.size != @rank raise ArgumentError.new("given #{idxary.size} params(#{idxary})" + " does not match rank: #{@rank}") end idx = 0 while idx < idxary.size if idxary[idx] + 1 > @size[idx] @size[idx] = idxary[idx] + 1 end idx += 1 end data = retrieve(idxary[0, idxary.size - 1]) data[idxary.last] = value if value.is_a?(SOAPType) value.elename = ITEM_NAME # Sync type unless @type.name @type = XSD::QName.new(value.type.namespace, SOAPArray.create_arytype(value.type.name, @rank)) end value.type ||= @type end @offset = idxary value.parent = self if value.respond_to?(:parent=) offsetnext end def each @data.each do |data| yield(data) end end def to_a @data.dup end def replace @data = deep_map(@data) do |ele| yield(ele) end end def deep_map(ary, &block) ary.collect do |ele| if ele.is_a?(Array) deep_map(ele, &block) else new_obj = block.call(ele) new_obj.elename = ITEM_NAME new_obj end end end def include?(var) traverse_data(@data) do |v, *rank| if v.is_a?(SOAPBasetype) && v.data == var return true end end false end def traverse traverse_data(@data) do |v, *rank| unless @sparse yield(v) else yield(v, *rank) if v && !v.is_a?(SOAPNil) end end end def soap2array(ary) traverse_data(@data) do |v, *position| iteary = ary rank = 1 while rank < position.size idx = position[rank - 1] if iteary[idx].nil? iteary = iteary[idx] = Array.new else iteary = iteary[idx] end rank += 1 end if block_given? iteary[position.last] = yield(v) else iteary[position.last] = v end end end def position @position end private ITEM_NAME = XSD::QName.new(nil, 'item') def retrieve(idxary) data = @data rank = 1 while rank <= idxary.size idx = idxary[rank - 1] if data[idx].nil? data = data[idx] = Array.new else data = data[idx] end rank += 1 end data end def traverse_data(data, rank = 1) idx = 0 while idx < ranksize(rank) if rank < @rank traverse_data(data[idx], rank + 1) do |*v| v[1, 0] = idx yield(*v) end else yield(data[idx], idx) end idx += 1 end end def ranksize(rank) @size[rank - 1] end def offsetnext move = false idx = @offset.size - 1 while !move && idx >= 0 @offset[idx] += 1 if @size_fixed if @offset[idx] < @size[idx] move = true else @offset[idx] = 0 idx -= 1 end else move = true end end end # Module function public def self.decode(elename, type, arytype) typestr, nofary = parse_type(arytype.name) rank = nofary.count(',') + 1 plain_arytype = XSD::QName.new(arytype.namespace, typestr) o = SOAPArray.new(type, rank, plain_arytype) size = [] nofary.split(',').each do |s| if s.empty? size.clear break else size << s.to_i end end unless size.empty? o.size = size o.size_fixed = true end o.elename = elename o end private def self.create_arytype(typename, rank) "#{typename}[" << ',' * (rank - 1) << ']' end TypeParseRegexp = Regexp.new('^(.+)\[([\d,]*)\]$') def self.parse_type(string) TypeParseRegexp =~ string return $1, $2 end end require 'soap/mapping/typeMap' 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/mimemessage.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/mimemessage.rb
# SOAP4R - MIME Message implementation. # Copyright (C) 2002 Jamie Herre. # 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/attachment' module SOAP # Classes for MIME message handling. Should be put somewhere else! # Tried using the 'tmail' module but found that I needed something # lighter in weight. class MIMEMessage class MIMEMessageError < StandardError; end MultipartContentType = 'multipart/\w+' class Header attr_accessor :str, :key, :root def initialize @attrs = {} end def [](key) @attrs[key] end def []=(key, value) @attrs[key] = value end def to_s @key + ": " + @str end end class Headers < Hash def self.parse(str) new.parse(str) end def parse(str) header_cache = nil str.each do |line| case line when /^\A[^\: \t]+:\s*.+$/ parse_line(header_cache) if header_cache header_cache = line.sub(/\r?\n\z/, '') when /^\A\s+(.*)$/ # a continuous line at the beginning line crashes here. header_cache << line else raise RuntimeError.new("unexpected header: #{line.inspect}") end end parse_line(header_cache) if header_cache self end def parse_line(line) if /^\A([^\: \t]+):\s*(.+)\z/ =~ line header = parse_rhs($2.strip) header.key = $1.strip self[header.key.downcase] = header else raise RuntimeError.new("unexpected header line: #{line.inspect}") end end def parse_rhs(str) a = str.split(/;+\s+/) header = Header.new header.str = str header.root = a.shift a.each do |pair| if pair =~ /(\w+)\s*=\s*"?([^"]+)"?/ header[$1.downcase] = $2 else raise RuntimeError.new("unexpected header component: #{pair.inspect}") end end header end def add(key, value) if key != nil and value != nil header = parse_rhs(value) header.key = key self[key.downcase] = header end end def to_s self.values.collect { |hdr| hdr.to_s }.join("\r\n") end end class Part attr_accessor :headers, :body def initialize @headers = Headers.new @headers.add("Content-Transfer-Encoding", "8bit") @body = nil @contentid = nil end def self.parse(str) new.parse(str) end def parse(str) headers, body = str.split(/\r\n\r\n/s) if headers != nil and body != nil @headers = Headers.parse(headers) @body = body.sub(/\r\n\z/, '') else raise RuntimeError.new("unexpected part: #{str.inspect}") end self end def contentid if @contentid == nil and @headers.key?('content-id') @contentid = @headers['content-id'].str @contentid = $1 if @contentid =~ /^<(.+)>$/ end @contentid end alias content body def to_s @headers.to_s + "\r\n\r\n" + @body end end def initialize @parts = [] @headers = Headers.new @root = nil end def self.parse(head, str) new.parse(head, str) end attr_reader :parts, :headers def close @headers.add( "Content-Type", "multipart/related; type=\"text/xml\"; boundary=\"#{boundary}\"; start=\"#{@parts[0].contentid}\"" ) end def parse(head, str) @headers = Headers.parse(head + "\r\n" + "From: jfh\r\n") boundary = @headers['content-type']['boundary'] if boundary != nil parts = str.split(/--#{Regexp.quote(boundary)}\s*(?:\r\n|--\r\n)/) part = parts.shift # preamble must be ignored. @parts = parts.collect { |part| Part.parse(part) } else @parts = [Part.parse(str)] end if @parts.length < 1 raise MIMEMessageError.new("This message contains no valid parts!") end self end def root if @root == nil start = @headers['content-type']['start'] @root = (start && @parts.find { |prt| prt.contentid == start }) || @parts[0] end @root end def boundary if @boundary == nil @boundary = "----=Part_" + __id__.to_s + rand.to_s end @boundary end def add_part(content) part = Part.new part.headers.add("Content-Type", "text/xml; charset=" + XSD::Charset.xml_encoding_label) part.headers.add("Content-ID", Attachment.contentid(part)) part.body = content @parts.unshift(part) end def add_attachment(attach) part = Part.new part.headers.add("Content-Type", attach.contenttype) part.headers.add("Content-ID", attach.mime_contentid) part.body = attach.content @parts.unshift(part) end def has_parts? (@parts.length > 0) end def headers_str @headers.to_s end def content_str str = '' @parts.each do |prt| str << "--" + boundary + "\r\n" str << prt.to_s + "\r\n" end str << '--' + boundary + "--\r\n" str end def to_s str = headers_str + "\r\n\r\n" + content_str 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/httpconfigloader.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/httpconfigloader.rb
# SOAP4R - HTTP config loader. # 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/property' module SOAP module HTTPConfigLoader module_function def set_options(client, options) client.proxy = options["proxy"] options.add_hook("proxy") do |key, value| client.proxy = value end client.no_proxy = options["no_proxy"] options.add_hook("no_proxy") do |key, value| client.no_proxy = value end if client.respond_to?(:protocol_version=) client.protocol_version = options["protocol_version"] options.add_hook("protocol_version") do |key, value| client.protocol_version = value end end ssl_config = options["ssl_config"] ||= ::SOAP::Property.new set_ssl_config(client, ssl_config) ssl_config.add_hook(true) do |key, value| set_ssl_config(client, ssl_config) end basic_auth = options["basic_auth"] ||= ::SOAP::Property.new set_basic_auth(client, basic_auth) basic_auth.add_hook do |key, value| set_basic_auth(client, basic_auth) end options.add_hook("connect_timeout") do |key, value| client.connect_timeout = value end options.add_hook("send_timeout") do |key, value| client.send_timeout = value end options.add_hook("receive_timeout") do |key, value| client.receive_timeout = value end end def set_basic_auth(client, basic_auth) basic_auth.values.each do |url, userid, passwd| client.set_basic_auth(url, userid, passwd) end end def set_ssl_config(client, ssl_config) ssl_config.each do |key, value| cfg = client.ssl_config if cfg.nil? raise NotImplementedError.new("SSL not supported") end case key when 'client_cert' cfg.client_cert = cert_from_file(value) when 'client_key' cfg.client_key = key_from_file(value) when 'client_ca' cfg.client_ca = value when 'ca_path' cfg.set_trust_ca(value) when 'ca_file' cfg.set_trust_ca(value) when 'crl' cfg.set_crl(value) when 'verify_mode' cfg.verify_mode = ssl_config_int(value) when 'verify_depth' cfg.verify_depth = ssl_config_int(value) when 'options' cfg.options = value when 'ciphers' cfg.ciphers = value when 'verify_callback' cfg.verify_callback = value when 'cert_store' cfg.cert_store = value else raise ArgumentError.new("unknown ssl_config property #{key}") end end end def ssl_config_int(value) if value.nil? or value.to_s.empty? nil else begin Integer(value) rescue ArgumentError ::SOAP::Property::Util.const_from_name(value.to_s) end end end def cert_from_file(filename) OpenSSL::X509::Certificate.new(File.open(filename) { |f| f.read }) end def key_from_file(filename) OpenSSL::PKey::RSA.new(File.open(filename) { |f| f.read }) 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/rubytypeFactory.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/mapping/rubytypeFactory.rb
# SOAP4R - Ruby type mapping factory. # 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. module SOAP module Mapping class RubytypeFactory < Factory TYPE_STRING = XSD::QName.new(RubyTypeNamespace, 'String') TYPE_TIME = XSD::QName.new(RubyTypeNamespace, 'Time') TYPE_ARRAY = XSD::QName.new(RubyTypeNamespace, 'Array') TYPE_REGEXP = XSD::QName.new(RubyTypeNamespace, 'Regexp') TYPE_RANGE = XSD::QName.new(RubyTypeNamespace, 'Range') TYPE_CLASS = XSD::QName.new(RubyTypeNamespace, 'Class') TYPE_MODULE = XSD::QName.new(RubyTypeNamespace, 'Module') TYPE_SYMBOL = XSD::QName.new(RubyTypeNamespace, 'Symbol') TYPE_STRUCT = XSD::QName.new(RubyTypeNamespace, 'Struct') TYPE_HASH = XSD::QName.new(RubyTypeNamespace, 'Map') def initialize(config = {}) @config = config @allow_untyped_struct = @config.key?(:allow_untyped_struct) ? @config[:allow_untyped_struct] : true @allow_original_mapping = @config.key?(:allow_original_mapping) ? @config[:allow_original_mapping] : false @string_factory = StringFactory_.new(true) @basetype_factory = BasetypeFactory_.new(true) @datetime_factory = DateTimeFactory_.new(true) @array_factory = ArrayFactory_.new(true) @hash_factory = HashFactory_.new(true) end def obj2soap(soap_class, obj, info, map) param = nil case obj when ::String unless @allow_original_mapping return nil end param = @string_factory.obj2soap(SOAPString, obj, info, map) if obj.class != String param.extraattr[RubyTypeName] = obj.class.name end addiv2soapattr(param, obj, map) when ::Time unless @allow_original_mapping return nil end param = @datetime_factory.obj2soap(SOAPDateTime, obj, info, map) if obj.class != Time param.extraattr[RubyTypeName] = obj.class.name end addiv2soapattr(param, obj, map) when ::Array unless @allow_original_mapping return nil end param = @array_factory.obj2soap(nil, obj, info, map) if obj.class != Array param.extraattr[RubyTypeName] = obj.class.name end addiv2soapattr(param, obj, map) when ::NilClass unless @allow_original_mapping return nil end param = @basetype_factory.obj2soap(SOAPNil, obj, info, map) addiv2soapattr(param, obj, map) when ::FalseClass, ::TrueClass unless @allow_original_mapping return nil end param = @basetype_factory.obj2soap(SOAPBoolean, obj, info, map) addiv2soapattr(param, obj, map) when ::Integer unless @allow_original_mapping return nil end param = @basetype_factory.obj2soap(SOAPInt, obj, info, map) param ||= @basetype_factory.obj2soap(SOAPInteger, obj, info, map) param ||= @basetype_factory.obj2soap(SOAPDecimal, obj, info, map) addiv2soapattr(param, obj, map) when ::Float unless @allow_original_mapping return nil end param = @basetype_factory.obj2soap(SOAPDouble, obj, info, map) if obj.class != Float param.extraattr[RubyTypeName] = obj.class.name end addiv2soapattr(param, obj, map) when ::Hash unless @allow_original_mapping return nil end if obj.respond_to?(:default_proc) && obj.default_proc raise TypeError.new("cannot dump hash with default proc") end param = SOAPStruct.new(TYPE_HASH) mark_marshalled_obj(obj, param) if obj.class != Hash param.extraattr[RubyTypeName] = obj.class.name end obj.each do |key, value| elem = SOAPStruct.new # Undefined type. elem.add("key", Mapping._obj2soap(key, map)) elem.add("value", Mapping._obj2soap(value, map)) param.add("item", elem) end param.add('default', Mapping._obj2soap(obj.default, map)) addiv2soapattr(param, obj, map) when ::Regexp unless @allow_original_mapping return nil end param = SOAPStruct.new(TYPE_REGEXP) mark_marshalled_obj(obj, param) if obj.class != Regexp param.extraattr[RubyTypeName] = obj.class.name end param.add('source', SOAPBase64.new(obj.source)) if obj.respond_to?('options') # Regexp#options is from Ruby/1.7 options = obj.options else options = 0 obj.inspect.sub(/^.*\//, '').each_byte do |c| options += case c when ?i 1 when ?x 2 when ?m 4 when ?n 16 when ?e 32 when ?s 48 when ?u 64 end end end param.add('options', SOAPInt.new(options)) addiv2soapattr(param, obj, map) when ::Range unless @allow_original_mapping return nil end param = SOAPStruct.new(TYPE_RANGE) mark_marshalled_obj(obj, param) if obj.class != Range param.extraattr[RubyTypeName] = obj.class.name end param.add('begin', Mapping._obj2soap(obj.begin, map)) param.add('end', Mapping._obj2soap(obj.end, map)) param.add('exclude_end', SOAP::SOAPBoolean.new(obj.exclude_end?)) addiv2soapattr(param, obj, map) when ::Class unless @allow_original_mapping return nil end if obj.to_s[0] == ?# raise TypeError.new("can't dump anonymous class #{obj}") end param = SOAPStruct.new(TYPE_CLASS) mark_marshalled_obj(obj, param) param.add('name', SOAPString.new(obj.name)) addiv2soapattr(param, obj, map) when ::Module unless @allow_original_mapping return nil end if obj.to_s[0] == ?# raise TypeError.new("can't dump anonymous module #{obj}") end param = SOAPStruct.new(TYPE_MODULE) mark_marshalled_obj(obj, param) param.add('name', SOAPString.new(obj.name)) addiv2soapattr(param, obj, map) when ::Symbol unless @allow_original_mapping return nil end param = SOAPStruct.new(TYPE_SYMBOL) mark_marshalled_obj(obj, param) param.add('id', SOAPString.new(obj.id2name)) addiv2soapattr(param, obj, map) when ::Struct unless @allow_original_mapping # treat it as an user defined class. [ruby-talk:104980] #param = unknownobj2soap(soap_class, obj, info, map) param = SOAPStruct.new(XSD::AnyTypeName) mark_marshalled_obj(obj, param) obj.members.each do |member| param.add(Mapping.name2elename(member), Mapping._obj2soap(obj[member], map)) end else param = SOAPStruct.new(TYPE_STRUCT) mark_marshalled_obj(obj, param) param.add('type', ele_type = SOAPString.new(obj.class.to_s)) ele_member = SOAPStruct.new obj.members.each do |member| ele_member.add(Mapping.name2elename(member), Mapping._obj2soap(obj[member], map)) end param.add('member', ele_member) addiv2soapattr(param, obj, map) end when ::IO, ::Binding, ::Continuation, ::Data, ::Dir, ::File::Stat, ::MatchData, Method, ::Proc, ::Thread, ::ThreadGroup # from 1.8: Process::Status, UnboundMethod return nil when ::SOAP::Mapping::Object param = SOAPStruct.new(XSD::AnyTypeName) mark_marshalled_obj(obj, param) obj.__xmlele.each do |key, value| param.add(key.name, Mapping._obj2soap(value, map)) end obj.__xmlattr.each do |key, value| param.extraattr[key] = value end when ::Exception typestr = Mapping.name2elename(obj.class.to_s) param = SOAPStruct.new(XSD::QName.new(RubyTypeNamespace, typestr)) mark_marshalled_obj(obj, param) param.add('message', Mapping._obj2soap(obj.message, map)) param.add('backtrace', Mapping._obj2soap(obj.backtrace, map)) addiv2soapattr(param, obj, map) else param = unknownobj2soap(soap_class, obj, info, map) end param end def soap2obj(obj_class, node, info, map) rubytype = node.extraattr[RubyTypeName] if rubytype or node.type.namespace == RubyTypeNamespace rubytype2obj(node, info, map, rubytype) elsif node.type == XSD::AnyTypeName or node.type == XSD::AnySimpleTypeName anytype2obj(node, info, map) else unknowntype2obj(node, info, map) end end private def addiv2soapattr(node, obj, map) return if obj.instance_variables.empty? ivars = SOAPStruct.new # Undefined type. setiv2soap(ivars, obj, map) node.extraattr[RubyIVarName] = ivars end def unknownobj2soap(soap_class, obj, info, map) if obj.class.name.empty? raise TypeError.new("can't dump anonymous class #{obj}") end singleton_class = class << obj; self; end if !singleton_methods_true(obj).empty? or !singleton_class.instance_variables.empty? raise TypeError.new("singleton can't be dumped #{obj}") end if !(singleton_class.ancestors - obj.class.ancestors).empty? typestr = Mapping.name2elename(obj.class.to_s) type = XSD::QName.new(RubyTypeNamespace, typestr) else type = Mapping.class2element(obj.class) end param = SOAPStruct.new(type) mark_marshalled_obj(obj, param) setiv2soap(param, obj, map) param end if RUBY_VERSION >= '1.8.0' def singleton_methods_true(obj) obj.singleton_methods(true) end else def singleton_methods_true(obj) obj.singleton_methods end end def rubytype2obj(node, info, map, rubytype) klass = rubytype ? Mapping.class_from_name(rubytype) : nil obj = nil case node when SOAPString return @string_factory.soap2obj(klass || String, node, info, map) when SOAPDateTime #return @datetime_factory.soap2obj(klass || Time, node, info, map) klass ||= Time t = node.to_time arg = [t.year, t.month, t.mday, t.hour, t.min, t.sec, t.usec] obj = t.gmt? ? klass.gm(*arg) : klass.local(*arg) mark_unmarshalled_obj(node, obj) return true, obj when SOAPArray return @array_factory.soap2obj(klass || Array, node, info, map) when SOAPNil, SOAPBoolean, SOAPInt, SOAPInteger, SOAPDecimal, SOAPDouble return @basetype_factory.soap2obj(nil, node, info, map) when SOAPStruct return rubytypestruct2obj(node, info, map, rubytype) else raise end end def rubytypestruct2obj(node, info, map, rubytype) klass = rubytype ? Mapping.class_from_name(rubytype) : nil obj = nil case node.type when TYPE_HASH klass = rubytype ? Mapping.class_from_name(rubytype) : Hash obj = Mapping.create_empty_object(klass) mark_unmarshalled_obj(node, obj) node.each do |key, value| next unless key == 'item' obj[Mapping._soap2obj(value['key'], map)] = Mapping._soap2obj(value['value'], map) end if node.key?('default') obj.default = Mapping._soap2obj(node['default'], map) end when TYPE_REGEXP klass = rubytype ? Mapping.class_from_name(rubytype) : Regexp obj = Mapping.create_empty_object(klass) mark_unmarshalled_obj(node, obj) source = node['source'].string options = node['options'].data || 0 Regexp.instance_method(:initialize).bind(obj).call(source, options) when TYPE_RANGE klass = rubytype ? Mapping.class_from_name(rubytype) : Range obj = Mapping.create_empty_object(klass) mark_unmarshalled_obj(node, obj) first = Mapping._soap2obj(node['begin'], map) last = Mapping._soap2obj(node['end'], map) exclude_end = node['exclude_end'].data Range.instance_method(:initialize).bind(obj).call(first, last, exclude_end) when TYPE_CLASS obj = Mapping.class_from_name(node['name'].data) when TYPE_MODULE obj = Mapping.class_from_name(node['name'].data) when TYPE_SYMBOL obj = node['id'].data.intern when TYPE_STRUCT typestr = Mapping.elename2name(node['type'].data) klass = Mapping.class_from_name(typestr) if klass.nil? return false end unless klass <= ::Struct return false end obj = Mapping.create_empty_object(klass) mark_unmarshalled_obj(node, obj) node['member'].each do |name, value| obj[Mapping.elename2name(name)] = Mapping._soap2obj(value, map) end else return unknowntype2obj(node, info, map) end return true, obj end def anytype2obj(node, info, map) case node when SOAPBasetype return true, node.data when SOAPStruct klass = ::SOAP::Mapping::Object obj = klass.new mark_unmarshalled_obj(node, obj) node.each do |name, value| obj.__add_xmlele_value(XSD::QName.new(nil, name), Mapping._soap2obj(value, map)) end unless node.extraattr.empty? obj.instance_variable_set('@__xmlattr', node.extraattr) end return true, obj else return false end end def unknowntype2obj(node, info, map) case node when SOAPBasetype return true, node.data when SOAPArray return @array_factory.soap2obj(Array, node, info, map) when SOAPStruct obj = unknownstruct2obj(node, info, map) return true, obj if obj if !@allow_untyped_struct return false end return anytype2obj(node, info, map) else # Basetype which is not defined... return false end end def unknownstruct2obj(node, info, map) unless node.type.name return nil end typestr = Mapping.elename2name(node.type.name) klass = Mapping.class_from_name(typestr) if klass.nil? and @allow_untyped_struct klass = Mapping.class_from_name(typestr, true) # lenient end if klass.nil? return nil end if klass <= ::Exception return exception2obj(klass, node, map) end klass_type = Mapping.class2qname(klass) return nil unless node.type.match(klass_type) obj = nil begin obj = Mapping.create_empty_object(klass) rescue # type name "data" tries Data.new which raises TypeError nil end mark_unmarshalled_obj(node, obj) setiv2obj(obj, node, map) obj end def exception2obj(klass, node, map) message = Mapping._soap2obj(node['message'], map) backtrace = Mapping._soap2obj(node['backtrace'], map) obj = Mapping.create_empty_object(klass) obj = obj.exception(message) mark_unmarshalled_obj(node, obj) obj.set_backtrace(backtrace) obj end # Only creates empty array. Do String#replace it with real string. def array2obj(node, map, rubytype) klass = rubytype ? Mapping.class_from_name(rubytype) : Array obj = Mapping.create_empty_object(klass) mark_unmarshalled_obj(node, obj) obj end # Only creates empty string. Do String#replace it with real string. def string2obj(node, map, rubytype) klass = rubytype ? Mapping.class_from_name(rubytype) : String obj = Mapping.create_empty_object(klass) mark_unmarshalled_obj(node, obj) obj 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/typeMap.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/mapping/typeMap.rb
# SOAP4R - Base type mapping definition # 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. module SOAP TypeMap = { XSD::XSDAnySimpleType::Type => SOAPAnySimpleType, XSD::XSDString::Type => SOAPString, XSD::XSDBoolean::Type => SOAPBoolean, XSD::XSDDecimal::Type => SOAPDecimal, XSD::XSDFloat::Type => SOAPFloat, XSD::XSDDouble::Type => SOAPDouble, XSD::XSDDuration::Type => SOAPDuration, XSD::XSDDateTime::Type => SOAPDateTime, XSD::XSDTime::Type => SOAPTime, XSD::XSDDate::Type => SOAPDate, XSD::XSDGYearMonth::Type => SOAPGYearMonth, XSD::XSDGYear::Type => SOAPGYear, XSD::XSDGMonthDay::Type => SOAPGMonthDay, XSD::XSDGDay::Type => SOAPGDay, XSD::XSDGMonth::Type => SOAPGMonth, XSD::XSDHexBinary::Type => SOAPHexBinary, XSD::XSDBase64Binary::Type => SOAPBase64, XSD::XSDAnyURI::Type => SOAPAnyURI, XSD::XSDQName::Type => SOAPQName, XSD::XSDInteger::Type => SOAPInteger, XSD::XSDNonPositiveInteger::Type => SOAPNonPositiveInteger, XSD::XSDNegativeInteger::Type => SOAPNegativeInteger, XSD::XSDLong::Type => SOAPLong, XSD::XSDInt::Type => SOAPInt, XSD::XSDShort::Type => SOAPShort, XSD::XSDByte::Type => SOAPByte, XSD::XSDNonNegativeInteger::Type => SOAPNonNegativeInteger, XSD::XSDUnsignedLong::Type => SOAPUnsignedLong, XSD::XSDUnsignedInt::Type => SOAPUnsignedInt, XSD::XSDUnsignedShort::Type => SOAPUnsignedShort, XSD::XSDUnsignedByte::Type => SOAPUnsignedByte, XSD::XSDPositiveInteger::Type => SOAPPositiveInteger, SOAP::SOAPBase64::Type => SOAPBase64, } 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/mapping.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/mapping/mapping.rb
# SOAP4R - Ruby type mapping utility. # 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/codegen/gensupport' module SOAP module Mapping RubyTypeNamespace = 'http://www.ruby-lang.org/xmlns/ruby/type/1.6' RubyTypeInstanceNamespace = 'http://www.ruby-lang.org/xmlns/ruby/type-instance' RubyCustomTypeNamespace = 'http://www.ruby-lang.org/xmlns/ruby/type/custom' ApacheSOAPTypeNamespace = 'http://xml.apache.org/xml-soap' # TraverseSupport breaks following thread variables. # Thread.current[:SOAPMarshalDataKey] module TraverseSupport def mark_marshalled_obj(obj, soap_obj) raise if obj.nil? Thread.current[:SOAPMarshalDataKey][obj.__id__] = soap_obj end def mark_unmarshalled_obj(node, obj) return if obj.nil? # node.id is not Object#id but SOAPReference#id Thread.current[:SOAPMarshalDataKey][node.id] = obj end end EMPTY_OPT = {} def self.obj2soap(obj, registry = nil, type = nil, opt = EMPTY_OPT) registry ||= Mapping::DefaultRegistry soap_obj = nil protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do Thread.current[:SOAPMarshalDataKey] = {} Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE Thread.current[:SOAPMarshalNoReference] = opt[:no_reference] soap_obj = _obj2soap(obj, registry, type) end soap_obj end def self.soap2obj(node, registry = nil, klass = nil, opt = EMPTY_OPT) registry ||= Mapping::DefaultRegistry obj = nil protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do Thread.current[:SOAPMarshalDataKey] = {} Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE Thread.current[:SOAPMarshalNoReference] = opt[:no_reference] obj = _soap2obj(node, registry, klass) end obj end def self.ary2soap(ary, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT) registry ||= Mapping::DefaultRegistry type = XSD::QName.new(type_ns, typename) soap_ary = SOAPArray.new(ValueArrayName, 1, type) protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do Thread.current[:SOAPMarshalDataKey] = {} Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE Thread.current[:SOAPMarshalNoReference] = opt[:no_reference] ary.each do |ele| soap_ary.add(_obj2soap(ele, registry, type)) end end soap_ary end def self.ary2md(ary, rank, type_ns = XSD::Namespace, typename = XSD::AnyTypeLiteral, registry = nil, opt = EMPTY_OPT) registry ||= Mapping::DefaultRegistry type = XSD::QName.new(type_ns, typename) md_ary = SOAPArray.new(ValueArrayName, rank, type) protect_threadvars(:SOAPMarshalDataKey, :SOAPExternalCES, :SOAPMarshalNoReference) do Thread.current[:SOAPMarshalDataKey] = {} Thread.current[:SOAPExternalCES] = opt[:external_ces] || $KCODE Thread.current[:SOAPMarshalNoReference] = opt[:no_reference] add_md_ary(md_ary, ary, [], registry) end md_ary end def self.fault2exception(fault, registry = nil) registry ||= Mapping::DefaultRegistry detail = if fault.detail soap2obj(fault.detail, registry) || "" else "" end if detail.is_a?(Mapping::SOAPException) begin e = detail.to_e remote_backtrace = e.backtrace e.set_backtrace(nil) raise e # ruby sets current caller as local backtrace of e => e2. rescue Exception => e e.set_backtrace(remote_backtrace + e.backtrace[1..-1]) raise end else fault.detail = detail fault.set_backtrace( if detail.is_a?(Array) detail else [detail.to_s] end ) raise end end def self._obj2soap(obj, registry, type = nil) if referent = Thread.current[:SOAPMarshalDataKey][obj.__id__] and !Thread.current[:SOAPMarshalNoReference] SOAPReference.new(referent) elsif registry registry.obj2soap(obj, type) else raise MappingError.new("no mapping registry given") end end def self._soap2obj(node, registry, klass = nil) if node.nil? return nil elsif node.is_a?(SOAPReference) target = node.__getobj__ # target.id is not Object#id but SOAPReference#id if referent = Thread.current[:SOAPMarshalDataKey][target.id] and !Thread.current[:SOAPMarshalNoReference] return referent else return _soap2obj(target, registry, klass) end end return registry.soap2obj(node, klass) end if Object.respond_to?(:allocate) # ruby/1.7 or later. def self.create_empty_object(klass) klass.allocate end else MARSHAL_TAG = { String => ['"', 1], Regexp => ['/', 2], Array => ['[', 1], Hash => ['{', 1] } def self.create_empty_object(klass) if klass <= Struct name = klass.name return ::Marshal.load(sprintf("\004\006S:%c%s\000", name.length + 5, name)) end if MARSHAL_TAG.has_key?(klass) tag, terminate = MARSHAL_TAG[klass] return ::Marshal.load(sprintf("\004\006%s%s", tag, "\000" * terminate)) end MARSHAL_TAG.each do |k, v| if klass < k name = klass.name tag, terminate = v return ::Marshal.load(sprintf("\004\006C:%c%s%s%s", name.length + 5, name, tag, "\000" * terminate)) end end name = klass.name ::Marshal.load(sprintf("\004\006o:%c%s\000", name.length + 5, name)) end end # Allow only (Letter | '_') (Letter | Digit | '-' | '_')* here. # Caution: '.' is not allowed here. # To follow XML spec., it should be NCName. # (denied chars) => .[0-F][0-F] # ex. a.b => a.2eb # def self.name2elename(name) name.gsub(/([^a-zA-Z0-9:_\-]+)/n) { '.' << $1.unpack('H2' * $1.size).join('.') }.gsub(/::/n, '..') end def self.elename2name(name) name.gsub(/\.\./n, '::').gsub(/((?:\.[0-9a-fA-F]{2})+)/n) { [$1.delete('.')].pack('H*') } end def self.const_from_name(name, lenient = false) const = ::Object name.sub(/\A::/, '').split('::').each do |const_str| if XSD::CodeGen::GenSupport.safeconstname?(const_str) if const.const_defined?(const_str) const = const.const_get(const_str) next end elsif lenient const_str = XSD::CodeGen::GenSupport.safeconstname(const_str) if const.const_defined?(const_str) const = const.const_get(const_str) next end end return nil end const end def self.class_from_name(name, lenient = false) const = const_from_name(name, lenient) if const.is_a?(::Class) const else nil end end def self.module_from_name(name, lenient = false) const = const_from_name(name, lenient) if const.is_a?(::Module) const else nil end end def self.class2qname(klass) name = schema_type_definition(klass) namespace = schema_ns_definition(klass) XSD::QName.new(namespace, name) end def self.class2element(klass) type = Mapping.class2qname(klass) type.name ||= Mapping.name2elename(klass.name) type.namespace ||= RubyCustomTypeNamespace type end def self.obj2element(obj) name = namespace = nil ivars = obj.instance_variables if ivars.include?('@schema_type') name = obj.instance_variable_get('@schema_type') end if ivars.include?('@schema_ns') namespace = obj.instance_variable_get('@schema_ns') end if !name or !namespace class2qname(obj.class) else XSD::QName.new(namespace, name) end end def self.define_singleton_method(obj, name, &block) sclass = (class << obj; self; end) sclass.class_eval { define_method(name, &block) } end def self.get_attribute(obj, attr_name) if obj.is_a?(::Hash) obj[attr_name] || obj[attr_name.intern] else name = XSD::CodeGen::GenSupport.safevarname(attr_name) if obj.instance_variables.include?('@' + name) obj.instance_variable_get('@' + name) elsif ((obj.is_a?(::Struct) or obj.is_a?(Marshallable)) and obj.respond_to?(name)) obj.__send__(name) end end end def self.set_attributes(obj, values) if obj.is_a?(::SOAP::Mapping::Object) values.each do |attr_name, value| obj.__add_xmlele_value(attr_name, value) end else values.each do |attr_name, value| name = XSD::CodeGen::GenSupport.safevarname(attr_name) setter = name + "=" if obj.respond_to?(setter) obj.__send__(setter, value) else obj.instance_variable_set('@' + name, value) begin define_attr_accessor(obj, name, proc { instance_variable_get('@' + name) }, proc { |value| instance_variable_set('@' + name, value) }) rescue TypeError # singleton class may not exist (e.g. Float) end end end end end def self.define_attr_accessor(obj, name, getterproc, setterproc = nil) define_singleton_method(obj, name, &getterproc) define_singleton_method(obj, name + '=', &setterproc) if setterproc end def self.schema_type_definition(klass) class_schema_variable(:schema_type, klass) end def self.schema_ns_definition(klass) class_schema_variable(:schema_ns, klass) end def self.schema_element_definition(klass) schema_element = class_schema_variable(:schema_element, klass) or return nil schema_ns = schema_ns_definition(klass) elements = [] as_array = [] schema_element.each do |varname, definition| class_name, name = definition if /\[\]$/ =~ class_name class_name = class_name.sub(/\[\]$/, '') as_array << (name ? name.name : varname) end elements << [name || XSD::QName.new(schema_ns, varname), class_name] end [elements, as_array] end def self.schema_attribute_definition(klass) class_schema_variable(:schema_attribute, klass) end class << Mapping private def class_schema_variable(sym, klass) var = "@@#{sym}" klass.class_variables.include?(var) ? klass.class_eval(var) : nil end def protect_threadvars(*symbols) backup = {} begin symbols.each do |sym| backup[sym] = Thread.current[sym] end yield ensure symbols.each do |sym| Thread.current[sym] = backup[sym] end end end def add_md_ary(md_ary, ary, indices, registry) for idx in 0..(ary.size - 1) if ary[idx].is_a?(Array) add_md_ary(md_ary, ary[idx], indices + [idx], registry) else md_ary[*(indices + [idx])] = _obj2soap(ary[idx], registry) 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/soap/mapping/registry.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/mapping/registry.rb
# SOAP4R - Mapping registry. # 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 'soap/baseData' require 'soap/mapping/mapping' require 'soap/mapping/typeMap' require 'soap/mapping/factory' require 'soap/mapping/rubytypeFactory' module SOAP module Marshallable # @@type_ns = Mapping::RubyCustomTypeNamespace end module Mapping module MappedException; end RubyTypeName = XSD::QName.new(RubyTypeInstanceNamespace, 'rubyType') RubyExtendName = XSD::QName.new(RubyTypeInstanceNamespace, 'extends') RubyIVarName = XSD::QName.new(RubyTypeInstanceNamespace, 'ivars') # Inner class to pass an exception. class SOAPException; include Marshallable attr_reader :excn_type_name, :cause def initialize(e) @excn_type_name = Mapping.name2elename(e.class.to_s) @cause = e end def to_e if @cause.is_a?(::Exception) @cause.extend(::SOAP::Mapping::MappedException) return @cause elsif @cause.respond_to?(:message) and @cause.respond_to?(:backtrace) e = RuntimeError.new(@cause.message) e.set_backtrace(@cause.backtrace) return e end klass = Mapping.class_from_name(Mapping.elename2name(@excn_type_name.to_s)) if klass.nil? or not klass <= ::Exception return RuntimeError.new(@cause.inspect) end obj = klass.new(@cause.message) obj.extend(::SOAP::Mapping::MappedException) obj end end # For anyType object: SOAP::Mapping::Object not ::Object class Object; include Marshallable def initialize @__xmlele_type = {} @__xmlele = [] @__xmlattr = {} end def inspect sprintf("#<%s:0x%x%s>", self.class.name, __id__, @__xmlele.collect { |name, value| " #{name}=#{value.inspect}" }.join) end def __xmlattr @__xmlattr end def __xmlele @__xmlele end def [](qname) unless qname.is_a?(XSD::QName) qname = XSD::QName.new(nil, qname) end @__xmlele.each do |k, v| return v if k == qname end # fallback @__xmlele.each do |k, v| return v if k.name == qname.name end nil end def []=(qname, value) unless qname.is_a?(XSD::QName) qname = XSD::QName.new(nil, qname) end found = false @__xmlele.each do |pair| if pair[0] == qname found = true pair[1] = value end end unless found __define_attr_accessor(qname) @__xmlele << [qname, value] end @__xmlele_type[qname] = :single end def __add_xmlele_value(qname, value) found = false @__xmlele.map! do |k, v| if k == qname found = true [k, __set_xmlele_value(k, v, value)] else [k, v] end end unless found __define_attr_accessor(qname) @__xmlele << [qname, value] @__xmlele_type[qname] = :single end value end private if RUBY_VERSION > "1.7.0" def __define_attr_accessor(qname) name = XSD::CodeGen::GenSupport.safemethodname(qname.name) Mapping.define_attr_accessor(self, name, proc { self[qname] }, proc { |value| self[qname] = value }) end else def __define_attr_accessor(qname) name = XSD::CodeGen::GenSupport.safemethodname(qname.name) instance_eval <<-EOS def #{name} self[#{qname.dump}] end def #{name}=(value) self[#{qname.dump}] = value end EOS end end def __set_xmlele_value(key, org, value) case @__xmlele_type[key] when :multi org << value org when :single @__xmlele_type[key] = :multi [org, value] else raise RuntimeError.new("unknown type") end end end class MappingError < Error; end class Registry class Map def initialize(registry) @obj2soap = {} @soap2obj = {} @registry = registry end def obj2soap(obj) klass = obj.class if map = @obj2soap[klass] map.each do |soap_class, factory, info| ret = factory.obj2soap(soap_class, obj, info, @registry) return ret if ret end end ancestors = klass.ancestors ancestors.delete(klass) ancestors.delete(::Object) ancestors.delete(::Kernel) ancestors.each do |klass| if map = @obj2soap[klass] map.each do |soap_class, factory, info| if info[:derived_class] ret = factory.obj2soap(soap_class, obj, info, @registry) return ret if ret end end end end nil end def soap2obj(node, klass = nil) if map = @soap2obj[node.class] map.each do |obj_class, factory, info| next if klass and obj_class != klass conv, obj = factory.soap2obj(obj_class, node, info, @registry) return true, obj if conv end end return false, nil end # Give priority to former entry. def init(init_map = []) clear init_map.reverse_each do |obj_class, soap_class, factory, info| add(obj_class, soap_class, factory, info) end end # Give priority to latter entry. def add(obj_class, soap_class, factory, info) info ||= {} (@obj2soap[obj_class] ||= []).unshift([soap_class, factory, info]) (@soap2obj[soap_class] ||= []).unshift([obj_class, factory, info]) end def clear @obj2soap.clear @soap2obj.clear end def find_mapped_soap_class(target_obj_class) map = @obj2soap[target_obj_class] map.empty? ? nil : map[0][1] end def find_mapped_obj_class(target_soap_class) map = @soap2obj[target_soap_class] map.empty? ? nil : map[0][0] end end StringFactory = StringFactory_.new BasetypeFactory = BasetypeFactory_.new DateTimeFactory = DateTimeFactory_.new ArrayFactory = ArrayFactory_.new Base64Factory = Base64Factory_.new URIFactory = URIFactory_.new TypedArrayFactory = TypedArrayFactory_.new TypedStructFactory = TypedStructFactory_.new HashFactory = HashFactory_.new SOAPBaseMap = [ [::NilClass, ::SOAP::SOAPNil, BasetypeFactory], [::TrueClass, ::SOAP::SOAPBoolean, BasetypeFactory], [::FalseClass, ::SOAP::SOAPBoolean, BasetypeFactory], [::String, ::SOAP::SOAPString, StringFactory], [::DateTime, ::SOAP::SOAPDateTime, DateTimeFactory], [::Date, ::SOAP::SOAPDate, DateTimeFactory], [::Time, ::SOAP::SOAPDateTime, DateTimeFactory], [::Time, ::SOAP::SOAPTime, DateTimeFactory], [::Float, ::SOAP::SOAPDouble, BasetypeFactory, {:derived_class => true}], [::Float, ::SOAP::SOAPFloat, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPInt, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPLong, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPShort, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPByte, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNonPositiveInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNegativeInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNonNegativeInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPPositiveInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedLong, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedInt, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedShort, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedByte, BasetypeFactory, {:derived_class => true}], [::URI::Generic, ::SOAP::SOAPAnyURI, URIFactory, {:derived_class => true}], [::String, ::SOAP::SOAPBase64, Base64Factory], [::String, ::SOAP::SOAPHexBinary, Base64Factory], [::String, ::SOAP::SOAPDecimal, BasetypeFactory], [::String, ::SOAP::SOAPDuration, BasetypeFactory], [::String, ::SOAP::SOAPGYearMonth, BasetypeFactory], [::String, ::SOAP::SOAPGYear, BasetypeFactory], [::String, ::SOAP::SOAPGMonthDay, BasetypeFactory], [::String, ::SOAP::SOAPGDay, BasetypeFactory], [::String, ::SOAP::SOAPGMonth, BasetypeFactory], [::String, ::SOAP::SOAPQName, BasetypeFactory], [::Hash, ::SOAP::SOAPArray, HashFactory], [::Hash, ::SOAP::SOAPStruct, HashFactory], [::Array, ::SOAP::SOAPArray, ArrayFactory, {:derived_class => true}], [::SOAP::Mapping::SOAPException, ::SOAP::SOAPStruct, TypedStructFactory, {:type => XSD::QName.new(RubyCustomTypeNamespace, "SOAPException")}], ] RubyOriginalMap = [ [::NilClass, ::SOAP::SOAPNil, BasetypeFactory], [::TrueClass, ::SOAP::SOAPBoolean, BasetypeFactory], [::FalseClass, ::SOAP::SOAPBoolean, BasetypeFactory], [::String, ::SOAP::SOAPString, StringFactory], [::DateTime, ::SOAP::SOAPDateTime, DateTimeFactory], [::Date, ::SOAP::SOAPDate, DateTimeFactory], [::Time, ::SOAP::SOAPDateTime, DateTimeFactory], [::Time, ::SOAP::SOAPTime, DateTimeFactory], [::Float, ::SOAP::SOAPDouble, BasetypeFactory, {:derived_class => true}], [::Float, ::SOAP::SOAPFloat, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPInt, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPLong, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPShort, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPByte, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNonPositiveInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNegativeInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPNonNegativeInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPPositiveInteger, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedLong, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedInt, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedShort, BasetypeFactory, {:derived_class => true}], [::Integer, ::SOAP::SOAPUnsignedByte, BasetypeFactory, {:derived_class => true}], [::URI::Generic, ::SOAP::SOAPAnyURI, URIFactory, {:derived_class => true}], [::String, ::SOAP::SOAPBase64, Base64Factory], [::String, ::SOAP::SOAPHexBinary, Base64Factory], [::String, ::SOAP::SOAPDecimal, BasetypeFactory], [::String, ::SOAP::SOAPDuration, BasetypeFactory], [::String, ::SOAP::SOAPGYearMonth, BasetypeFactory], [::String, ::SOAP::SOAPGYear, BasetypeFactory], [::String, ::SOAP::SOAPGMonthDay, BasetypeFactory], [::String, ::SOAP::SOAPGDay, BasetypeFactory], [::String, ::SOAP::SOAPGMonth, BasetypeFactory], [::String, ::SOAP::SOAPQName, BasetypeFactory], [::Hash, ::SOAP::SOAPArray, HashFactory], [::Hash, ::SOAP::SOAPStruct, HashFactory], # Does not allow Array's subclass here. [::Array, ::SOAP::SOAPArray, ArrayFactory], [::SOAP::Mapping::SOAPException, ::SOAP::SOAPStruct, TypedStructFactory, {:type => XSD::QName.new(RubyCustomTypeNamespace, "SOAPException")}], ] attr_accessor :default_factory attr_accessor :excn_handler_obj2soap attr_accessor :excn_handler_soap2obj def initialize(config = {}) @config = config @map = Map.new(self) if @config[:allow_original_mapping] @allow_original_mapping = true @map.init(RubyOriginalMap) else @allow_original_mapping = false @map.init(SOAPBaseMap) end @allow_untyped_struct = @config.key?(:allow_untyped_struct) ? @config[:allow_untyped_struct] : true @rubytype_factory = RubytypeFactory.new( :allow_untyped_struct => @allow_untyped_struct, :allow_original_mapping => @allow_original_mapping ) @default_factory = @rubytype_factory @excn_handler_obj2soap = nil @excn_handler_soap2obj = nil end def add(obj_class, soap_class, factory, info = nil) @map.add(obj_class, soap_class, factory, info) end alias set add # general Registry ignores type_qname def obj2soap(obj, type_qname = nil) soap = _obj2soap(obj) if @allow_original_mapping addextend2soap(soap, obj) end soap end def soap2obj(node, klass = nil) obj = _soap2obj(node, klass) if @allow_original_mapping addextend2obj(obj, node.extraattr[RubyExtendName]) addiv2obj(obj, node.extraattr[RubyIVarName]) end obj end def find_mapped_soap_class(obj_class) @map.find_mapped_soap_class(obj_class) end def find_mapped_obj_class(soap_class) @map.find_mapped_obj_class(soap_class) end private def _obj2soap(obj) ret = nil if obj.is_a?(SOAPStruct) or obj.is_a?(SOAPArray) obj.replace do |ele| Mapping._obj2soap(ele, self) end return obj elsif obj.is_a?(SOAPBasetype) return obj end begin ret = @map.obj2soap(obj) || @default_factory.obj2soap(nil, obj, nil, self) return ret if ret rescue MappingError end if @excn_handler_obj2soap ret = @excn_handler_obj2soap.call(obj) { |yield_obj| Mapping._obj2soap(yield_obj, self) } return ret if ret end raise MappingError.new("Cannot map #{ obj.class.name } to SOAP/OM.") end # Might return nil as a mapping result. def _soap2obj(node, klass = nil) if node.extraattr.key?(RubyTypeName) conv, obj = @rubytype_factory.soap2obj(nil, node, nil, self) return obj if conv else conv, obj = @map.soap2obj(node, klass) return obj if conv conv, obj = @default_factory.soap2obj(nil, node, nil, self) return obj if conv end if @excn_handler_soap2obj begin return @excn_handler_soap2obj.call(node) { |yield_node| Mapping._soap2obj(yield_node, self) } rescue Exception end end raise MappingError.new("Cannot map #{ node.type.name } to Ruby object.") end def addiv2obj(obj, attr) return unless attr vars = {} attr.__getobj__.each do |name, value| vars[name] = Mapping._soap2obj(value, self) end Mapping.set_attributes(obj, vars) end if RUBY_VERSION >= '1.8.0' def addextend2obj(obj, attr) return unless attr attr.split(/ /).reverse_each do |mstr| obj.extend(Mapping.module_from_name(mstr)) end end else # (class < false; self; end).ancestors includes "TrueClass" under 1.6... def addextend2obj(obj, attr) return unless attr attr.split(/ /).reverse_each do |mstr| m = Mapping.module_from_name(mstr) obj.extend(m) end end end def addextend2soap(node, obj) return if obj.is_a?(Symbol) or obj.is_a?(Fixnum) list = (class << obj; self; end).ancestors - obj.class.ancestors unless list.empty? node.extraattr[RubyExtendName] = list.collect { |c| if c.name.empty? raise TypeError.new("singleton can't be dumped #{ obj }") end c.name }.join(" ") end end end DefaultRegistry = Registry.new RubyOriginalRegistry = Registry.new(:allow_original_mapping => true) 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/wsdlliteralregistry.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/mapping/wsdlliteralregistry.rb
# SOAP4R - WSDL literal mapping registry. # 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 'soap/baseData' require 'soap/mapping/mapping' require 'soap/mapping/typeMap' require 'xsd/codegen/gensupport' require 'xsd/namedelements' module SOAP module Mapping class WSDLLiteralRegistry < Registry attr_reader :definedelements attr_reader :definedtypes attr_accessor :excn_handler_obj2soap attr_accessor :excn_handler_soap2obj def initialize(definedtypes = XSD::NamedElements::Empty, definedelements = XSD::NamedElements::Empty) @definedtypes = definedtypes @definedelements = definedelements @excn_handler_obj2soap = nil @excn_handler_soap2obj = nil @schema_element_cache = {} @schema_attribute_cache = {} end def obj2soap(obj, qname) soap_obj = nil if ele = @definedelements[qname] soap_obj = obj2elesoap(obj, ele) elsif type = @definedtypes[qname] soap_obj = obj2typesoap(obj, type, true) else soap_obj = any2soap(obj, qname) end return soap_obj if soap_obj if @excn_handler_obj2soap soap_obj = @excn_handler_obj2soap.call(obj) { |yield_obj| Mapping.obj2soap(yield_obj, nil, nil, MAPPING_OPT) } return soap_obj if soap_obj end raise MappingError.new("cannot map #{obj.class.name} as #{qname}") end # node should be a SOAPElement def soap2obj(node, obj_class = nil) # obj_class is given when rpc/literal service. but ignored for now. begin return any2obj(node) rescue MappingError end if @excn_handler_soap2obj begin return @excn_handler_soap2obj.call(node) { |yield_node| Mapping.soap2obj(yield_node, nil, nil, MAPPING_OPT) } rescue Exception end end if node.respond_to?(:type) raise MappingError.new("cannot map #{node.type.name} to Ruby object") else raise MappingError.new("cannot map #{node.elename.name} to Ruby object") end end private MAPPING_OPT = { :no_reference => true } def obj2elesoap(obj, ele) o = nil qualified = (ele.elementform == 'qualified') if ele.type if type = @definedtypes[ele.type] o = obj2typesoap(obj, type, qualified) elsif type = TypeMap[ele.type] o = base2soap(obj, type) else raise MappingError.new("cannot find type #{ele.type}") end elsif ele.local_complextype o = obj2typesoap(obj, ele.local_complextype, qualified) add_attributes2soap(obj, o) elsif ele.local_simpletype o = obj2typesoap(obj, ele.local_simpletype, qualified) else raise MappingError.new('illegal schema?') end o.elename = ele.name o end def obj2typesoap(obj, type, qualified) if type.is_a?(::WSDL::XMLSchema::SimpleType) simpleobj2soap(obj, type) else complexobj2soap(obj, type, qualified) end end def simpleobj2soap(obj, type) type.check_lexical_format(obj) return SOAPNil.new if obj.nil? # ToDo: check nillable. o = base2soap(obj, TypeMap[type.base]) o end def complexobj2soap(obj, type, qualified) o = SOAPElement.new(type.name) o.qualified = qualified type.each_element do |child_ele| child = Mapping.get_attribute(obj, child_ele.name.name) if child.nil? if child_ele.nillable # ToDo: test # add empty element child_soap = obj2elesoap(nil, child_ele) o.add(child_soap) elsif Integer(child_ele.minoccurs) == 0 # nothing to do else raise MappingError.new("nil not allowed: #{child_ele.name.name}") end elsif child_ele.map_as_array? child.each do |item| child_soap = obj2elesoap(item, child_ele) o.add(child_soap) end else child_soap = obj2elesoap(child, child_ele) o.add(child_soap) end end o end def any2soap(obj, qname) if obj.is_a?(SOAPElement) obj elsif obj.class.class_variables.include?('@@schema_element') stubobj2soap(obj, qname) elsif obj.is_a?(SOAP::Mapping::Object) mappingobj2soap(obj, qname) elsif obj.is_a?(Hash) ele = SOAPElement.from_obj(obj) ele.elename = qname ele else # expected to be a basetype or an anyType. # SOAPStruct, etc. is used instead of SOAPElement. begin ele = Mapping.obj2soap(obj, nil, nil, MAPPING_OPT) ele.elename = qname ele rescue MappingError ele = SOAPElement.new(qname, obj.to_s) end if obj.respond_to?(:__xmlattr) obj.__xmlattr.each do |key, value| ele.extraattr[key] = value end end ele end end def stubobj2soap(obj, qname) ele = SOAPElement.new(qname) ele.qualified = (obj.class.class_variables.include?('@@schema_qualified') and obj.class.class_eval('@@schema_qualified')) add_elements2soap(obj, ele) add_attributes2soap(obj, ele) ele end def mappingobj2soap(obj, qname) ele = SOAPElement.new(qname) obj.__xmlele.each do |key, value| if value.is_a?(::Array) value.each do |item| ele.add(obj2soap(item, key)) end else ele.add(obj2soap(value, key)) end end obj.__xmlattr.each do |key, value| ele.extraattr[key] = value end ele end def add_elements2soap(obj, ele) elements, as_array = schema_element_definition(obj.class) if elements elements.each do |elename, type| if child = Mapping.get_attribute(obj, elename.name) if as_array.include?(elename.name) child.each do |item| ele.add(obj2soap(item, elename)) end else ele.add(obj2soap(child, elename)) end elsif obj.is_a?(::Array) and as_array.include?(elename.name) obj.each do |item| ele.add(obj2soap(item, elename)) end end end end end def add_attributes2soap(obj, ele) attributes = schema_attribute_definition(obj.class) if attributes attributes.each do |qname, param| attr = obj.__send__('xmlattr_' + XSD::CodeGen::GenSupport.safevarname(qname.name)) ele.extraattr[qname] = attr end end end def base2soap(obj, type) soap_obj = nil if type <= XSD::XSDString str = XSD::Charset.encoding_conv(obj.to_s, Thread.current[:SOAPExternalCES], XSD::Charset.encoding) soap_obj = type.new(str) else soap_obj = type.new(obj) end soap_obj end def anytype2obj(node) if node.is_a?(::SOAP::SOAPBasetype) return node.data end klass = ::SOAP::Mapping::Object obj = klass.new obj end def any2obj(node, obj_class = nil) unless obj_class typestr = XSD::CodeGen::GenSupport.safeconstname(node.elename.name) obj_class = Mapping.class_from_name(typestr) end if obj_class and obj_class.class_variables.include?('@@schema_element') soapele2stubobj(node, obj_class) elsif node.is_a?(SOAPElement) or node.is_a?(SOAPStruct) # SOAPArray for literal? soapele2plainobj(node) else obj = Mapping.soap2obj(node, nil, obj_class, MAPPING_OPT) add_attributes2plainobj(node, obj) obj end end def soapele2stubobj(node, obj_class) obj = Mapping.create_empty_object(obj_class) add_elements2stubobj(node, obj) add_attributes2stubobj(node, obj) obj end def soapele2plainobj(node) obj = anytype2obj(node) add_elements2plainobj(node, obj) add_attributes2plainobj(node, obj) obj end def add_elements2stubobj(node, obj) elements, as_array = schema_element_definition(obj.class) vars = {} node.each do |name, value| item = elements.find { |k, v| k.name == name } if item elename, class_name = item if klass = Mapping.class_from_name(class_name) # klass must be a SOAPBasetype or a class if klass.ancestors.include?(::SOAP::SOAPBasetype) if value.respond_to?(:data) child = klass.new(value.data).data else child = klass.new(nil).data end else child = any2obj(value, klass) end elsif klass = Mapping.module_from_name(class_name) # simpletype if value.respond_to?(:data) child = value.data else raise MappingError.new( "cannot map to a module value: #{class_name}") end else raise MappingError.new("unknown class/module: #{class_name}") end else # untyped element is treated as anyType. child = any2obj(value) end if as_array.include?(elename.name) (vars[name] ||= []) << child else vars[name] = child end end Mapping.set_attributes(obj, vars) end def add_attributes2stubobj(node, obj) if attributes = schema_attribute_definition(obj.class) define_xmlattr(obj) attributes.each do |qname, class_name| attr = node.extraattr[qname] next if attr.nil? or attr.empty? klass = Mapping.class_from_name(class_name) if klass.ancestors.include?(::SOAP::SOAPBasetype) child = klass.new(attr).data else child = attr end obj.__xmlattr[qname] = child define_xmlattr_accessor(obj, qname) end end end def add_elements2plainobj(node, obj) node.each do |name, value| obj.__add_xmlele_value(value.elename, any2obj(value)) end end def add_attributes2plainobj(node, obj) return if node.extraattr.empty? define_xmlattr(obj) node.extraattr.each do |qname, value| obj.__xmlattr[qname] = value define_xmlattr_accessor(obj, qname) end end if RUBY_VERSION > "1.7.0" def define_xmlattr_accessor(obj, qname) name = XSD::CodeGen::GenSupport.safemethodname(qname.name) Mapping.define_attr_accessor(obj, 'xmlattr_' + name, proc { @__xmlattr[qname] }, proc { |value| @__xmlattr[qname] = value }) end else def define_xmlattr_accessor(obj, qname) name = XSD::CodeGen::GenSupport.safemethodname(qname.name) obj.instance_eval <<-EOS def #{name} @__xmlattr[#{qname.dump}] end def #{name}=(value) @__xmlattr[#{qname.dump}] = value end EOS end end if RUBY_VERSION > "1.7.0" def define_xmlattr(obj) obj.instance_variable_set('@__xmlattr', {}) unless obj.respond_to?(:__xmlattr) Mapping.define_attr_accessor(obj, :__xmlattr, proc { @__xmlattr }) end end else def define_xmlattr(obj) obj.instance_variable_set('@__xmlattr', {}) unless obj.respond_to?(:__xmlattr) obj.instance_eval <<-EOS def __xmlattr @__xmlattr end EOS end end end # it caches @@schema_element. this means that @@schema_element must not be # changed while a lifetime of a WSDLLiteralRegistry. def schema_element_definition(klass) @schema_element_cache[klass] ||= Mapping.schema_element_definition(klass) end def schema_attribute_definition(klass) @schema_attribute_cache[klass] ||= Mapping.schema_attribute_definition(klass) 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/factory.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/mapping/factory.rb
# SOAP4R - Mapping factory. # 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. module SOAP module Mapping class Factory include TraverseSupport def initialize # nothing to do end def obj2soap(soap_class, obj, info, map) raise NotImplementError.new # return soap_obj end def soap2obj(obj_class, node, info, map) raise NotImplementError.new # return convert_succeeded_or_not, obj end def setiv2obj(obj, node, map) return if node.nil? if obj.is_a?(Array) setiv2ary(obj, node, map) else setiv2struct(obj, node, map) end end def setiv2soap(node, obj, map) if obj.class.class_variables.include?('@@schema_element') obj.class.class_eval('@@schema_element').each do |name, info| type, qname = info if qname elename = qname.name else elename = Mapping.name2elename(name) end node.add(elename, Mapping._obj2soap(obj.instance_variable_get('@' + name), map)) end else # should we sort instance_variables? obj.instance_variables.each do |var| name = var.sub(/^@/, '') elename = Mapping.name2elename(name) node.add(elename, Mapping._obj2soap(obj.instance_variable_get(var), map)) end end end private def setiv2ary(obj, node, map) node.each do |name, value| Array.instance_method(:<<).bind(obj).call(Mapping._soap2obj(value, map)) end end def setiv2struct(obj, node, map) vars = {} node.each do |name, value| vars[Mapping.elename2name(name)] = Mapping._soap2obj(value, map) end Mapping.set_attributes(obj, vars) end end class StringFactory_ < Factory def initialize(allow_original_mapping = false) super() @allow_original_mapping = allow_original_mapping end def obj2soap(soap_class, obj, info, map) if !@allow_original_mapping and !obj.instance_variables.empty? return nil end begin unless XSD::Charset.is_ces(obj, Thread.current[:SOAPExternalCES]) return nil end encoded = XSD::Charset.encoding_conv(obj, Thread.current[:SOAPExternalCES], XSD::Charset.encoding) soap_obj = soap_class.new(encoded) rescue XSD::ValueSpaceError return nil end mark_marshalled_obj(obj, soap_obj) soap_obj end def soap2obj(obj_class, node, info, map) obj = Mapping.create_empty_object(obj_class) decoded = XSD::Charset.encoding_conv(node.data, XSD::Charset.encoding, Thread.current[:SOAPExternalCES]) obj.replace(decoded) mark_unmarshalled_obj(node, obj) return true, obj end end class BasetypeFactory_ < Factory def initialize(allow_original_mapping = false) super() @allow_original_mapping = allow_original_mapping end def obj2soap(soap_class, obj, info, map) if !@allow_original_mapping and !obj.instance_variables.empty? return nil end soap_obj = nil begin soap_obj = soap_class.new(obj) rescue XSD::ValueSpaceError return nil end if @allow_original_mapping # Basetype except String should not be multiref-ed in SOAP/1.1. mark_marshalled_obj(obj, soap_obj) end soap_obj end def soap2obj(obj_class, node, info, map) obj = node.data mark_unmarshalled_obj(node, obj) return true, obj end end class DateTimeFactory_ < Factory def initialize(allow_original_mapping = false) super() @allow_original_mapping = allow_original_mapping end def obj2soap(soap_class, obj, info, map) if !@allow_original_mapping and Time === obj and !obj.instance_variables.empty? return nil end soap_obj = nil begin soap_obj = soap_class.new(obj) rescue XSD::ValueSpaceError return nil end mark_marshalled_obj(obj, soap_obj) soap_obj end def soap2obj(obj_class, node, info, map) if node.respond_to?(:to_obj) obj = node.to_obj(obj_class) return false if obj.nil? mark_unmarshalled_obj(node, obj) return true, obj else return false end end end class Base64Factory_ < Factory def obj2soap(soap_class, obj, info, map) return nil unless obj.instance_variables.empty? soap_obj = soap_class.new(obj) mark_marshalled_obj(obj, soap_obj) if soap_obj soap_obj end def soap2obj(obj_class, node, info, map) obj = node.string mark_unmarshalled_obj(node, obj) return true, obj end end class URIFactory_ < Factory def obj2soap(soap_class, obj, info, map) soap_obj = soap_class.new(obj) mark_marshalled_obj(obj, soap_obj) if 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 class ArrayFactory_ < Factory def initialize(allow_original_mapping = false) super() @allow_original_mapping = allow_original_mapping end # [[1], [2]] is converted to Array of Array, not 2-D Array. # To create M-D Array, you must call Mapping.ary2md. def obj2soap(soap_class, obj, info, map) if !@allow_original_mapping and !obj.instance_variables.empty? return nil end arytype = Mapping.obj2element(obj) if arytype.name arytype.namespace ||= RubyTypeNamespace else arytype = XSD::AnyTypeName end soap_obj = SOAPArray.new(ValueArrayName, 1, arytype) mark_marshalled_obj(obj, soap_obj) obj.each do |item| soap_obj.add(Mapping._obj2soap(item, map)) end soap_obj end def soap2obj(obj_class, node, info, map) obj = Mapping.create_empty_object(obj_class) mark_unmarshalled_obj(node, obj) node.soap2array(obj) do |elem| elem ? Mapping._soap2obj(elem, map) : nil end return true, obj end end class TypedArrayFactory_ < Factory def initialize(allow_original_mapping = false) super() @allow_original_mapping = allow_original_mapping end def obj2soap(soap_class, obj, info, map) if !@allow_original_mapping and !obj.instance_variables.empty? return nil end arytype = info[:type] || info[0] soap_obj = SOAPArray.new(ValueArrayName, 1, arytype) mark_marshalled_obj(obj, soap_obj) obj.each do |var| soap_obj.add(Mapping._obj2soap(var, map)) end soap_obj end def soap2obj(obj_class, node, info, map) if node.rank > 1 return false end arytype = info[:type] || info[0] unless node.arytype == arytype return false end obj = Mapping.create_empty_object(obj_class) mark_unmarshalled_obj(node, obj) node.soap2array(obj) do |elem| elem ? Mapping._soap2obj(elem, map) : nil end return true, obj end end class TypedStructFactory_ < Factory def obj2soap(soap_class, obj, info, map) type = info[:type] || info[0] soap_obj = soap_class.new(type) mark_marshalled_obj(obj, soap_obj) if obj.class <= SOAP::Marshallable setiv2soap(soap_obj, obj, map) else setiv2soap(soap_obj, obj, map) end soap_obj end def soap2obj(obj_class, node, info, map) type = info[:type] || info[0] unless node.type == type return false end obj = Mapping.create_empty_object(obj_class) mark_unmarshalled_obj(node, obj) setiv2obj(obj, node, map) return true, obj end end MapQName = XSD::QName.new(ApacheSOAPTypeNamespace, 'Map') class HashFactory_ < Factory def initialize(allow_original_mapping = false) super() @allow_original_mapping = allow_original_mapping end def obj2soap(soap_class, obj, info, map) if !@allow_original_mapping and !obj.instance_variables.empty? return nil end if !obj.default.nil? or (obj.respond_to?(:default_proc) and obj.default_proc) return nil end soap_obj = SOAPStruct.new(MapQName) mark_marshalled_obj(obj, soap_obj) obj.each do |key, value| elem = SOAPStruct.new elem.add("key", Mapping._obj2soap(key, map)) elem.add("value", Mapping._obj2soap(value, map)) # ApacheAxis allows only 'item' here. soap_obj.add("item", elem) end soap_obj end def soap2obj(obj_class, node, info, map) unless node.type == MapQName return false end if node.class == SOAPStruct and node.key?('default') return false end obj = Mapping.create_empty_object(obj_class) mark_unmarshalled_obj(node, obj) if node.class == SOAPStruct node.each do |key, value| obj[Mapping._soap2obj(value['key'], map)] = Mapping._soap2obj(value['value'], map) end else node.each do |value| obj[Mapping._soap2obj(value['key'], map)] = Mapping._soap2obj(value['value'], map) end end return true, obj 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/wsdlencodedregistry.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/mapping/wsdlencodedregistry.rb
# SOAP4R - WSDL encoded mapping registry. # 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/qname' require 'xsd/namedelements' require 'soap/baseData' require 'soap/mapping/mapping' require 'soap/mapping/typeMap' module SOAP module Mapping class WSDLEncodedRegistry < Registry include TraverseSupport attr_reader :definedelements attr_reader :definedtypes attr_accessor :excn_handler_obj2soap attr_accessor :excn_handler_soap2obj def initialize(definedtypes = XSD::NamedElements::Empty) @definedtypes = definedtypes # @definedelements = definedelements needed? @excn_handler_obj2soap = nil @excn_handler_soap2obj = nil # For mapping AnyType element. @rubytype_factory = RubytypeFactory.new( :allow_untyped_struct => true, :allow_original_mapping => true ) @schema_element_cache = {} end def obj2soap(obj, qname = nil) soap_obj = nil if type = @definedtypes[qname] soap_obj = obj2typesoap(obj, type) else soap_obj = any2soap(obj, qname) end return soap_obj if soap_obj if @excn_handler_obj2soap soap_obj = @excn_handler_obj2soap.call(obj) { |yield_obj| Mapping._obj2soap(yield_obj, self) } return soap_obj if soap_obj end if qname raise MappingError.new("cannot map #{obj.class.name} as #{qname}") else raise MappingError.new("cannot map #{obj.class.name} to SOAP/OM") end end # map anything for now: must refer WSDL while mapping. [ToDo] def soap2obj(node, obj_class = nil) begin return any2obj(node, obj_class) rescue MappingError end if @excn_handler_soap2obj begin return @excn_handler_soap2obj.call(node) { |yield_node| Mapping._soap2obj(yield_node, self) } rescue Exception end end raise MappingError.new("cannot map #{node.type.name} to Ruby object") end private def any2soap(obj, qname) if obj.nil? SOAPNil.new elsif qname.nil? or qname == XSD::AnyTypeName @rubytype_factory.obj2soap(nil, obj, nil, self) elsif obj.is_a?(XSD::NSDBase) soap2soap(obj, qname) elsif (type = TypeMap[qname]) base2soap(obj, type) else nil end end def soap2soap(obj, type_qname) if obj.is_a?(SOAPBasetype) obj elsif obj.is_a?(SOAPStruct) && (type = @definedtypes[type_qname]) soap_obj = obj mark_marshalled_obj(obj, soap_obj) elements2soap(obj, soap_obj, type.content.elements) soap_obj elsif obj.is_a?(SOAPArray) && (type = @definedtypes[type_qname]) soap_obj = obj contenttype = type.child_type mark_marshalled_obj(obj, soap_obj) obj.replace do |ele| Mapping._obj2soap(ele, self, contenttype) end soap_obj else nil end end def obj2typesoap(obj, type) if type.is_a?(::WSDL::XMLSchema::SimpleType) simpleobj2soap(obj, type) else complexobj2soap(obj, type) end end def simpleobj2soap(obj, type) type.check_lexical_format(obj) return SOAPNil.new if obj.nil? # ToDo: check nillable. o = base2soap(obj, TypeMap[type.base]) o end def complexobj2soap(obj, type) case type.compoundtype when :TYPE_STRUCT struct2soap(obj, type.name, type) when :TYPE_ARRAY array2soap(obj, type.name, type) when :TYPE_MAP map2soap(obj, type.name, type) when :TYPE_SIMPLE simpleobj2soap(obj, type.simplecontent) when :TYPE_EMPTY raise MappingError.new("should be empty") unless obj.nil? SOAPNil.new else raise MappingError.new("unknown compound type: #{type.compoundtype}") end end def base2soap(obj, type) soap_obj = nil if type <= XSD::XSDString str = XSD::Charset.encoding_conv(obj.to_s, Thread.current[:SOAPExternalCES], XSD::Charset.encoding) soap_obj = type.new(str) mark_marshalled_obj(obj, soap_obj) else soap_obj = type.new(obj) end soap_obj end def struct2soap(obj, type_qname, type) return SOAPNil.new if obj.nil? # ToDo: check nillable. soap_obj = SOAPStruct.new(type_qname) unless obj.nil? mark_marshalled_obj(obj, soap_obj) elements2soap(obj, soap_obj, type.content.elements) end soap_obj end def array2soap(obj, type_qname, type) return SOAPNil.new if obj.nil? # ToDo: check nillable. arytype = type.child_type soap_obj = SOAPArray.new(ValueArrayName, 1, arytype) unless obj.nil? mark_marshalled_obj(obj, soap_obj) obj.each do |item| soap_obj.add(Mapping._obj2soap(item, self, arytype)) end end soap_obj end MapKeyName = XSD::QName.new(nil, "key") MapValueName = XSD::QName.new(nil, "value") def map2soap(obj, type_qname, type) return SOAPNil.new if obj.nil? # ToDo: check nillable. keytype = type.child_type(MapKeyName) || XSD::AnyTypeName valuetype = type.child_type(MapValueName) || XSD::AnyTypeName soap_obj = SOAPStruct.new(MapQName) unless obj.nil? mark_marshalled_obj(obj, soap_obj) obj.each do |key, value| elem = SOAPStruct.new elem.add("key", Mapping._obj2soap(key, self, keytype)) elem.add("value", Mapping._obj2soap(value, self, valuetype)) # ApacheAxis allows only 'item' here. soap_obj.add("item", elem) end end soap_obj end def elements2soap(obj, soap_obj, elements) elements.each do |element| name = element.name.name child_obj = Mapping.get_attribute(obj, name) soap_obj.add(name, Mapping._obj2soap(child_obj, self, element.type || element.name)) end end def any2obj(node, obj_class) unless obj_class typestr = XSD::CodeGen::GenSupport.safeconstname(node.elename.name) obj_class = Mapping.class_from_name(typestr) end if obj_class and obj_class.class_variables.include?('@@schema_element') soap2stubobj(node, obj_class) else Mapping._soap2obj(node, Mapping::DefaultRegistry, obj_class) end end def soap2stubobj(node, obj_class) obj = Mapping.create_empty_object(obj_class) unless node.is_a?(SOAPNil) add_elements2stubobj(node, obj) end obj end def add_elements2stubobj(node, obj) elements, as_array = schema_element_definition(obj.class) vars = {} node.each do |name, value| item = elements.find { |k, v| k.name == name } if item elename, class_name = item if klass = Mapping.class_from_name(class_name) # klass must be a SOAPBasetype or a class if klass.ancestors.include?(::SOAP::SOAPBasetype) if value.respond_to?(:data) child = klass.new(value.data).data else child = klass.new(nil).data end else child = Mapping._soap2obj(value, self, klass) end elsif klass = Mapping.module_from_name(class_name) # simpletype if value.respond_to?(:data) child = value.data else raise MappingError.new( "cannot map to a module value: #{class_name}") end else raise MappingError.new("unknown class: #{class_name}") end else # untyped element is treated as anyType. child = Mapping._soap2obj(value, self) end vars[name] = child end Mapping.set_attributes(obj, vars) end # it caches @@schema_element. this means that @@schema_element must not be # changed while a lifetime of a WSDLLiteralRegistry. def schema_element_definition(klass) @schema_element_cache[klass] ||= Mapping.schema_element_definition(klass) 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/rpc/element.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/rpc/element.rb
# SOAP4R - RPC element definition. # 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 'soap/baseData' module SOAP # Add method definitions for RPC to common definition in element.rb class SOAPBody < SOAPStruct public def request root_node end def response root = root_node if !@is_fault if root.nil? nil elsif root.is_a?(SOAPBasetype) root else # Initial element is [retval]. root[0] end else root end end def outparams root = root_node if !@is_fault and !root.nil? and !root.is_a?(SOAPBasetype) op = root[1..-1] op = nil if op && op.empty? op else nil end end def fault if @is_fault self['fault'] else nil end end def fault=(fault) @is_fault = true add_member('fault', fault) end end module RPC class RPCError < Error; end class MethodDefinitionError < RPCError; end class ParameterError < RPCError; end class SOAPMethod < SOAPStruct RETVAL = 'retval' IN = 'in' OUT = 'out' INOUT = 'inout' attr_reader :param_def attr_reader :inparam attr_reader :outparam attr_reader :retval_name attr_reader :retval_class_name def initialize(qname, param_def = nil) super(nil) @elename = qname @encodingstyle = nil @param_def = param_def @signature = [] @inparam_names = [] @inoutparam_names = [] @outparam_names = [] @inparam = {} @outparam = {} @retval_name = nil @retval_class_name = nil init_param(@param_def) if @param_def end def have_outparam? @outparam_names.size > 0 end def input_params collect_params(IN, INOUT) end def output_params collect_params(OUT, INOUT) end def set_param(params) params.each do |param, data| @inparam[param] = data data.elename.name = param data.parent = self end end def set_outparam(params) params.each do |param, data| @outparam[param] = data data.elename.name = param end end def SOAPMethod.param_count(param_def, *type) count = 0 param_def.each do |io_type, name, param_type| if type.include?(io_type) count += 1 end end count end def SOAPMethod.derive_rpc_param_def(obj, name, *param) if param.size == 1 and param[0].is_a?(Array) return param[0] end if param.empty? method = obj.method(name) param_names = (1..method.arity.abs).collect { |i| "p#{i}" } else param_names = param end create_rpc_param_def(param_names) end def SOAPMethod.create_rpc_param_def(param_names) param_def = [] param_names.each do |param_name| param_def.push([IN, param_name, nil]) end param_def.push([RETVAL, 'return', nil]) param_def end def SOAPMethod.create_doc_param_def(req_qnames, res_qnames) req_qnames = [req_qnames] if req_qnames.is_a?(XSD::QName) res_qnames = [res_qnames] if res_qnames.is_a?(XSD::QName) param_def = [] req_qnames.each do |qname| param_def << [IN, qname.name, [nil, qname.namespace, qname.name]] end res_qnames.each do |qname| param_def << [OUT, qname.name, [nil, qname.namespace, qname.name]] end param_def end private def collect_params(*type) names = [] @signature.each do |io_type, name, param_type| names << name if type.include?(io_type) end names end def init_param(param_def) param_def.each do |io_type, name, param_type| case io_type when IN @signature.push([IN, name, param_type]) @inparam_names.push(name) when OUT @signature.push([OUT, name, param_type]) @outparam_names.push(name) when INOUT @signature.push([INOUT, name, param_type]) @inoutparam_names.push(name) when RETVAL if @retval_name raise MethodDefinitionError.new('duplicated retval') end @retval_name = name @retval_class_name = nil if param_type if param_type[0].is_a?(String) @retval_class_name = Mapping.class_from_name(param_type[0]) else @retval_class_name = param_type[0] end end else raise MethodDefinitionError.new("unknown type: #{io_type}") end end end end class SOAPMethodRequest < SOAPMethod attr_accessor :soapaction def SOAPMethodRequest.create_request(qname, *params) param_def = [] param_value = [] i = 0 params.each do |param| param_name = "p#{i}" i += 1 param_def << [IN, param_name, nil] param_value << [param_name, param] end param_def << [RETVAL, 'return', nil] o = new(qname, param_def) o.set_param(param_value) o end def initialize(qname, param_def = nil, soapaction = nil) check_elename(qname) super(qname, param_def) @soapaction = soapaction end def each input_params.each do |name| unless @inparam[name] raise ParameterError.new("parameter: #{name} was not given") end yield(name, @inparam[name]) end end def dup req = self.class.new(@elename.dup, @param_def, @soapaction) req.encodingstyle = @encodingstyle req end def create_method_response(response_name = nil) response_name ||= XSD::QName.new(@elename.namespace, @elename.name + 'Response') SOAPMethodResponse.new(response_name, @param_def) end private def check_elename(qname) # NCName & ruby's method name unless /\A[\w_][\w\d_\-]*\z/ =~ qname.name raise MethodDefinitionError.new("element name '#{qname.name}' not allowed") end end end class SOAPMethodResponse < SOAPMethod def initialize(qname, param_def = nil) super(qname, param_def) @retval = nil end def retval=(retval) @retval = retval @retval.elename = @retval.elename.dup_name(@retval_name || 'return') retval.parent = self retval end def each if @retval_name and !@retval.is_a?(SOAPVoid) yield(@retval_name, @retval) end output_params.each do |name| unless @outparam[name] raise ParameterError.new("parameter: #{name} was not given") end yield(name, @outparam[name]) end end end # To return(?) void explicitly. # def foo(input_var) # ... # return SOAP::RPC::SOAPVoid.new # end class SOAPVoid < XSD::XSDAnySimpleType include SOAPBasetype extend SOAPModuleUtils Name = XSD::QName.new(Mapping::RubyCustomTypeNamespace, nil) public def initialize() @elename = Name @id = nil @precedents = [] @parent = 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/soap/rpc/standaloneServer.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/rpc/standaloneServer.rb
# SOAP4R - WEBrick Server # Copyright (C) 2003 by 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/rpc/httpserver' module SOAP module RPC class StandaloneServer < HTTPServer def initialize(appname, default_namespace, host = "0.0.0.0", port = 8080) @appname = appname @default_namespace = default_namespace @host = host @port = port super(create_config) end alias add_servant add_rpc_servant alias add_headerhandler add_rpc_headerhandler private def create_config { :BindAddress => @host, :Port => @port, :AccessLog => [], :SOAPDefaultNamespace => @default_namespace, :SOAPHTTPServerApplicationName => @appname, } 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/rpc/rpc.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/rpc/rpc.rb
# SOAP4R - RPC 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. module SOAP module RPC ServerException = Mapping::MappedException def self.defined_methods(obj) if obj.is_a?(Module) obj.methods - Module.methods else obj.methods - Object.instance_methods(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/soap/rpc/driver.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/rpc/driver.rb
# SOAP4R - SOAP RPC driver # 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 'soap/soap' require 'soap/mapping' require 'soap/mapping/wsdlliteralregistry' require 'soap/rpc/rpc' require 'soap/rpc/proxy' require 'soap/rpc/element' require 'soap/streamHandler' require 'soap/property' require 'soap/header/handlerset' module SOAP module RPC class Driver class << self if RUBY_VERSION >= "1.7.0" def __attr_proxy(symbol, assignable = false) name = symbol.to_s define_method(name) { @proxy.__send__(name) } if assignable aname = name + '=' define_method(aname) { |rhs| @proxy.__send__(aname, rhs) } end end else def __attr_proxy(symbol, assignable = false) name = symbol.to_s module_eval <<-EOS def #{name} @proxy.#{name} end EOS if assignable module_eval <<-EOS def #{name}=(value) @proxy.#{name} = value end EOS end end end end __attr_proxy :endpoint_url, true __attr_proxy :mapping_registry, true __attr_proxy :default_encodingstyle, true __attr_proxy :generate_explicit_type, true __attr_proxy :allow_unqualified_element, true __attr_proxy :headerhandler __attr_proxy :streamhandler __attr_proxy :test_loopback_response __attr_proxy :reset_stream attr_reader :proxy attr_reader :options attr_accessor :soapaction def inspect "#<#{self.class}:#{@proxy.inspect}>" end def httpproxy options["protocol.http.proxy"] end def httpproxy=(httpproxy) options["protocol.http.proxy"] = httpproxy end def wiredump_dev options["protocol.http.wiredump_dev"] end def wiredump_dev=(wiredump_dev) options["protocol.http.wiredump_dev"] = wiredump_dev end def mandatorycharset options["protocol.mandatorycharset"] end def mandatorycharset=(mandatorycharset) options["protocol.mandatorycharset"] = mandatorycharset end def wiredump_file_base options["protocol.wiredump_file_base"] end def wiredump_file_base=(wiredump_file_base) options["protocol.wiredump_file_base"] = wiredump_file_base end def initialize(endpoint_url, namespace = nil, soapaction = nil) @namespace = namespace @soapaction = soapaction @options = setup_options @wiredump_file_base = nil @proxy = Proxy.new(endpoint_url, @soapaction, @options) end def loadproperty(propertyname) unless options.loadproperty(propertyname) raise LoadError.new("No such property to load -- #{propertyname}") end end def add_rpc_method(name, *params) add_rpc_method_with_soapaction_as(name, name, @soapaction, *params) end def add_rpc_method_as(name, name_as, *params) add_rpc_method_with_soapaction_as(name, name_as, @soapaction, *params) end def add_rpc_method_with_soapaction(name, soapaction, *params) add_rpc_method_with_soapaction_as(name, name, soapaction, *params) end def add_rpc_method_with_soapaction_as(name, name_as, soapaction, *params) param_def = SOAPMethod.create_rpc_param_def(params) qname = XSD::QName.new(@namespace, name_as) @proxy.add_rpc_method(qname, soapaction, name, param_def) add_rpc_method_interface(name, param_def) end # add_method is for shortcut of typical rpc/encoded method definition. alias add_method add_rpc_method alias add_method_as add_rpc_method_as alias add_method_with_soapaction add_rpc_method_with_soapaction alias add_method_with_soapaction_as add_rpc_method_with_soapaction_as def add_document_method(name, soapaction, req_qname, res_qname) param_def = SOAPMethod.create_doc_param_def(req_qname, res_qname) @proxy.add_document_method(soapaction, name, param_def) add_document_method_interface(name, param_def) end def add_rpc_operation(qname, soapaction, name, param_def, opt = {}) @proxy.add_rpc_operation(qname, soapaction, name, param_def, opt) add_rpc_method_interface(name, param_def) end def add_document_operation(soapaction, name, param_def, opt = {}) @proxy.add_document_operation(soapaction, name, param_def, opt) add_document_method_interface(name, param_def) end def invoke(headers, body) if headers and !headers.is_a?(SOAPHeader) headers = create_header(headers) end set_wiredump_file_base(body.elename.name) env = @proxy.invoke(headers, body) if env.nil? return nil, nil else return env.header, env.body end end def call(name, *params) set_wiredump_file_base(name) @proxy.call(name, *params) end private def set_wiredump_file_base(name) if @wiredump_file_base @proxy.set_wiredump_file_base("#{@wiredump_file_base}_#{name}") end end def create_header(headers) header = SOAPHeader.new() headers.each do |content, mustunderstand, encodingstyle| header.add(SOAPHeaderItem.new(content, mustunderstand, encodingstyle)) end header 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| @proxy.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 def add_rpc_method_interface(name, param_def) param_count = RPC::SOAPMethod.param_count(param_def, RPC::SOAPMethod::IN, RPC::SOAPMethod::INOUT) add_method_interface(name, param_count) end def add_document_method_interface(name, param_def) param_count = RPC::SOAPMethod.param_count(param_def, RPC::SOAPMethod::IN) add_method_interface(name, param_count) end if RUBY_VERSION > "1.7.0" def add_method_interface(name, param_count) ::SOAP::Mapping.define_singleton_method(self, name) do |*arg| unless arg.size == param_count raise ArgumentError.new( "wrong number of arguments (#{arg.size} for #{param_count})") end call(name, *arg) end self.method(name) end else def add_method_interface(name, param_count) instance_eval <<-EOS def #{name}(*arg) unless arg.size == #{param_count} raise ArgumentError.new( "wrong number of arguments (\#{arg.size} for #{param_count})") end call(#{name.dump}, *arg) end EOS self.method(name) 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/soap/rpc/proxy.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/rpc/proxy.rb
# SOAP4R - RPC Proxy 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 'soap/soap' require 'soap/processor' require 'soap/mapping' require 'soap/rpc/rpc' require 'soap/rpc/element' require 'soap/streamHandler' require 'soap/mimemessage' module SOAP module RPC class Proxy include SOAP public attr_accessor :soapaction attr_accessor :mandatorycharset attr_accessor :allow_unqualified_element attr_accessor :default_encodingstyle attr_accessor :generate_explicit_type attr_reader :headerhandler attr_reader :streamhandler attr_accessor :mapping_registry attr_accessor :literal_mapping_registry attr_reader :operation def initialize(endpoint_url, soapaction, options) @endpoint_url = endpoint_url @soapaction = soapaction @options = options @streamhandler = HTTPStreamHandler.new( @options["protocol.http"] ||= ::SOAP::Property.new) @operation = {} @mandatorycharset = nil @allow_unqualified_element = true @default_encodingstyle = nil @generate_explicit_type = true @headerhandler = Header::HandlerSet.new @mapping_registry = nil @literal_mapping_registry = ::SOAP::Mapping::WSDLLiteralRegistry.new end def inspect "#<#{self.class}:#{@endpoint_url}>" end def endpoint_url @endpoint_url end def endpoint_url=(endpoint_url) @endpoint_url = endpoint_url reset_stream end def reset_stream @streamhandler.reset(@endpoint_url) end def set_wiredump_file_base(wiredump_file_base) @streamhandler.wiredump_file_base = wiredump_file_base end def test_loopback_response @streamhandler.test_loopback_response end def add_rpc_operation(qname, soapaction, name, param_def, opt = {}) opt[:request_qname] = qname opt[:request_style] ||= :rpc opt[:response_style] ||= :rpc opt[:request_use] ||= :encoded opt[:response_use] ||= :encoded @operation[name] = Operation.new(soapaction, param_def, opt) end def add_document_operation(soapaction, name, param_def, opt = {}) opt[:request_style] ||= :document opt[:response_style] ||= :document opt[:request_use] ||= :literal opt[:response_use] ||= :literal # default values of these values are unqualified in XML Schema. # set true for backward compatibility. unless opt.key?(:elementformdefault) opt[:elementformdefault] = true end unless opt.key?(:attributeformdefault) opt[:attributeformdefault] = true end @operation[name] = Operation.new(soapaction, param_def, opt) end # add_method is for shortcut of typical rpc/encoded method definition. alias add_method add_rpc_operation alias add_rpc_method add_rpc_operation alias add_document_method add_document_operation def invoke(req_header, req_body, opt = nil) opt ||= create_encoding_opt route(req_header, req_body, opt, opt) end def call(name, *params) unless op_info = @operation[name] raise MethodDefinitionError, "method: #{name} not defined" end mapping_opt = create_mapping_opt req_header = create_request_header req_body = SOAPBody.new( op_info.request_body(params, @mapping_registry, @literal_mapping_registry, mapping_opt) ) reqopt = create_encoding_opt( :soapaction => op_info.soapaction || @soapaction, :envelopenamespace => @options["soap.envelope.requestnamespace"], :default_encodingstyle => @default_encodingstyle || op_info.request_default_encodingstyle, :elementformdefault => op_info.elementformdefault, :attributeformdefault => op_info.attributeformdefault ) resopt = create_encoding_opt( :envelopenamespace => @options["soap.envelope.responsenamespace"], :default_encodingstyle => @default_encodingstyle || op_info.response_default_encodingstyle, :elementformdefault => op_info.elementformdefault, :attributeformdefault => op_info.attributeformdefault ) env = route(req_header, req_body, reqopt, resopt) raise EmptyResponseError unless env receive_headers(env.header) begin check_fault(env.body) rescue ::SOAP::FaultError => e op_info.raise_fault(e, @mapping_registry, @literal_mapping_registry) end op_info.response_obj(env.body, @mapping_registry, @literal_mapping_registry, mapping_opt) end def route(req_header, req_body, reqopt, resopt) req_env = ::SOAP::SOAPEnvelope.new(req_header, req_body) unless reqopt[:envelopenamespace].nil? set_envelopenamespace(req_env, reqopt[:envelopenamespace]) end reqopt[:external_content] = nil conn_data = marshal(req_env, reqopt) if ext = reqopt[:external_content] mime = MIMEMessage.new ext.each do |k, v| mime.add_attachment(v.data) end mime.add_part(conn_data.send_string + "\r\n") mime.close conn_data.send_string = mime.content_str conn_data.send_contenttype = mime.headers['content-type'].str end conn_data = @streamhandler.send(@endpoint_url, conn_data, reqopt[:soapaction]) if conn_data.receive_string.empty? return nil end unmarshal(conn_data, resopt) end def check_fault(body) if body.fault raise SOAP::FaultError.new(body.fault) end end private def set_envelopenamespace(env, namespace) env.elename = XSD::QName.new(namespace, env.elename.name) if env.header env.header.elename = XSD::QName.new(namespace, env.header.elename.name) end if env.body env.body.elename = XSD::QName.new(namespace, env.body.elename.name) end end def create_request_header headers = @headerhandler.on_outbound if headers.empty? nil else h = ::SOAP::SOAPHeader.new headers.each do |header| h.add(header.elename.name, header) end h end end def receive_headers(headers) @headerhandler.on_inbound(headers) if headers end def marshal(env, opt) send_string = Processor.marshal(env, opt) StreamHandler::ConnectionData.new(send_string) end def unmarshal(conn_data, opt) contenttype = conn_data.receive_contenttype if /#{MIMEMessage::MultipartContentType}/i =~ contenttype opt[:external_content] = {} mime = MIMEMessage.parse("Content-Type: " + contenttype, conn_data.receive_string) mime.parts.each do |part| value = Attachment.new(part.content) value.contentid = part.contentid obj = SOAPAttachment.new(value) opt[:external_content][value.contentid] = obj if value.contentid end opt[:charset] = @mandatorycharset || StreamHandler.parse_media_type(mime.root.headers['content-type'].str) env = Processor.unmarshal(mime.root.content, opt) else opt[:charset] = @mandatorycharset || ::SOAP::StreamHandler.parse_media_type(contenttype) env = Processor.unmarshal(conn_data.receive_string, opt) end unless env.is_a?(::SOAP::SOAPEnvelope) raise ResponseFormatError.new( "response is not a SOAP envelope: #{conn_data.receive_string}") end env end def create_header(headers) header = SOAPHeader.new() headers.each do |content, mustunderstand, encodingstyle| header.add(SOAPHeaderItem.new(content, mustunderstand, encodingstyle)) end header end def create_encoding_opt(hash = nil) opt = {} opt[:default_encodingstyle] = @default_encodingstyle opt[:allow_unqualified_element] = @allow_unqualified_element opt[:generate_explicit_type] = @generate_explicit_type opt[:no_indent] = @options["soap.envelope.no_indent"] opt[:use_numeric_character_reference] = @options["soap.envelope.use_numeric_character_reference"] opt.update(hash) if hash opt end def create_mapping_opt(hash = nil) opt = { :external_ces => @options["soap.mapping.external_ces"] } opt.update(hash) if hash opt end class Operation attr_reader :soapaction attr_reader :request_style attr_reader :response_style attr_reader :request_use attr_reader :response_use attr_reader :elementformdefault attr_reader :attributeformdefault def initialize(soapaction, param_def, opt) @soapaction = soapaction @request_style = opt[:request_style] @response_style = opt[:response_style] @request_use = opt[:request_use] @response_use = opt[:response_use] # set nil(unqualified) by default @elementformdefault = opt[:elementformdefault] @attributeformdefault = opt[:attributeformdefault] check_style(@request_style) check_style(@response_style) check_use(@request_use) check_use(@response_use) if @request_style == :rpc @rpc_request_qname = opt[:request_qname] if @rpc_request_qname.nil? raise MethodDefinitionError.new("rpc_request_qname must be given") end @rpc_method_factory = RPC::SOAPMethodRequest.new(@rpc_request_qname, param_def, @soapaction) else @doc_request_qnames = [] @doc_request_qualified = [] @doc_response_qnames = [] @doc_response_qualified = [] param_def.each do |inout, paramname, typeinfo, eleinfo| klass_not_used, nsdef, namedef = typeinfo qualified = eleinfo if namedef.nil? raise MethodDefinitionError.new("qname must be given") end case inout when SOAPMethod::IN @doc_request_qnames << XSD::QName.new(nsdef, namedef) @doc_request_qualified << qualified when SOAPMethod::OUT @doc_response_qnames << XSD::QName.new(nsdef, namedef) @doc_response_qualified << qualified else raise MethodDefinitionError.new( "illegal inout definition for document style: #{inout}") end end end end def request_default_encodingstyle (@request_use == :encoded) ? EncodingNamespace : LiteralNamespace end def response_default_encodingstyle (@response_use == :encoded) ? EncodingNamespace : LiteralNamespace end def request_body(values, mapping_registry, literal_mapping_registry, opt) if @request_style == :rpc request_rpc(values, mapping_registry, literal_mapping_registry, opt) else request_doc(values, mapping_registry, literal_mapping_registry, opt) end end def response_obj(body, mapping_registry, literal_mapping_registry, opt) if @response_style == :rpc response_rpc(body, mapping_registry, literal_mapping_registry, opt) else response_doc(body, mapping_registry, literal_mapping_registry, opt) end end def raise_fault(e, mapping_registry, literal_mapping_registry) if @response_style == :rpc Mapping.fault2exception(e, mapping_registry) else Mapping.fault2exception(e, literal_mapping_registry) end end private def check_style(style) unless [:rpc, :document].include?(style) raise MethodDefinitionError.new("unknown style: #{style}") end end def check_use(use) unless [:encoded, :literal].include?(use) raise MethodDefinitionError.new("unknown use: #{use}") end end def request_rpc(values, mapping_registry, literal_mapping_registry, opt) if @request_use == :encoded request_rpc_enc(values, mapping_registry, opt) else request_rpc_lit(values, literal_mapping_registry, opt) end end def request_doc(values, mapping_registry, literal_mapping_registry, opt) if @request_use == :encoded request_doc_enc(values, mapping_registry, opt) else request_doc_lit(values, literal_mapping_registry, opt) end end def request_rpc_enc(values, mapping_registry, opt) method = @rpc_method_factory.dup names = method.input_params obj = create_request_obj(names, values) soap = Mapping.obj2soap(obj, mapping_registry, @rpc_request_qname, opt) method.set_param(soap) method end def request_rpc_lit(values, mapping_registry, opt) method = @rpc_method_factory.dup params = {} idx = 0 method.input_params.each do |name| params[name] = Mapping.obj2soap(values[idx], mapping_registry, XSD::QName.new(nil, name), opt) idx += 1 end method.set_param(params) method end def request_doc_enc(values, mapping_registry, opt) (0...values.size).collect { |idx| ele = Mapping.obj2soap(values[idx], mapping_registry, nil, opt) ele.elename = @doc_request_qnames[idx] ele } end def request_doc_lit(values, mapping_registry, opt) (0...values.size).collect { |idx| ele = Mapping.obj2soap(values[idx], mapping_registry, @doc_request_qnames[idx], opt) ele.encodingstyle = LiteralNamespace if ele.respond_to?(:qualified) ele.qualified = @doc_request_qualified[idx] end ele } end def response_rpc(body, mapping_registry, literal_mapping_registry, opt) if @response_use == :encoded response_rpc_enc(body, mapping_registry, opt) else response_rpc_lit(body, literal_mapping_registry, opt) end end def response_doc(body, mapping_registry, literal_mapping_registry, opt) if @response_use == :encoded return *response_doc_enc(body, mapping_registry, opt) else return *response_doc_lit(body, literal_mapping_registry, opt) end end def response_rpc_enc(body, mapping_registry, opt) ret = nil if body.response ret = Mapping.soap2obj(body.response, mapping_registry, @rpc_method_factory.retval_class_name, opt) end if body.outparams outparams = body.outparams.collect { |outparam| Mapping.soap2obj(outparam, mapping_registry, nil, opt) } [ret].concat(outparams) else ret end end def response_rpc_lit(body, mapping_registry, opt) body.root_node.collect { |key, value| Mapping.soap2obj(value, mapping_registry, @rpc_method_factory.retval_class_name, opt) } end def response_doc_enc(body, mapping_registry, opt) body.collect { |key, value| Mapping.soap2obj(value, mapping_registry, nil, opt) } end def response_doc_lit(body, mapping_registry, opt) body.collect { |key, value| Mapping.soap2obj(value, mapping_registry) } end def create_request_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 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/rpc/router.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/rpc/router.rb
# SOAP4R - RPC Routing library # Copyright (C) 2001, 2002, 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 'soap/soap' require 'soap/processor' require 'soap/mapping' require 'soap/mapping/wsdlliteralregistry' require 'soap/rpc/rpc' require 'soap/rpc/element' require 'soap/streamHandler' require 'soap/mimemessage' require 'soap/header/handlerset' module SOAP module RPC class Router include SOAP attr_reader :actor attr_accessor :mapping_registry attr_accessor :literal_mapping_registry attr_accessor :generate_explicit_type attr_accessor :external_ces def initialize(actor) @actor = actor @mapping_registry = nil @headerhandler = Header::HandlerSet.new @literal_mapping_registry = ::SOAP::Mapping::WSDLLiteralRegistry.new @generate_explicit_type = true @external_ces = nil @operation_by_soapaction = {} @operation_by_qname = {} @headerhandlerfactory = [] end ### ## header handler interface # def add_request_headerhandler(factory) unless factory.respond_to?(:create) raise TypeError.new("factory must respond to 'create'") end @headerhandlerfactory << factory end def add_headerhandler(handler) @headerhandler.add(handler) end ### ## servant definition interface # def add_rpc_request_servant(factory, namespace) unless factory.respond_to?(:create) raise TypeError.new("factory must respond to 'create'") end obj = factory.create # a dummy instance for introspection ::SOAP::RPC.defined_methods(obj).each do |name| begin qname = XSD::QName.new(namespace, name) param_def = ::SOAP::RPC::SOAPMethod.derive_rpc_param_def(obj, name) opt = create_styleuse_option(:rpc, :encoded) add_rpc_request_operation(factory, qname, nil, name, param_def, opt) rescue SOAP::RPC::MethodDefinitionError => e p e if $DEBUG end end end def add_rpc_servant(obj, namespace) ::SOAP::RPC.defined_methods(obj).each do |name| begin qname = XSD::QName.new(namespace, name) param_def = ::SOAP::RPC::SOAPMethod.derive_rpc_param_def(obj, name) opt = create_styleuse_option(:rpc, :encoded) add_rpc_operation(obj, qname, nil, name, param_def, opt) rescue SOAP::RPC::MethodDefinitionError => e p e if $DEBUG end end end alias add_servant add_rpc_servant ### ## operation definition interface # def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {}) ensure_styleuse_option(opt, :rpc, :encoded) opt[:request_qname] = qname op = ApplicationScopeOperation.new(soapaction, receiver, name, param_def, opt) if opt[:request_style] != :rpc raise RPCRoutingError.new("illegal request_style given") end assign_operation(soapaction, qname, op) end alias add_method add_rpc_operation alias add_rpc_method add_rpc_operation def add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt = {}) ensure_styleuse_option(opt, :rpc, :encoded) opt[:request_qname] = qname op = RequestScopeOperation.new(soapaction, factory, name, param_def, opt) if opt[:request_style] != :rpc raise RPCRoutingError.new("illegal request_style given") end assign_operation(soapaction, qname, op) end def add_document_operation(receiver, soapaction, name, param_def, opt = {}) # # adopt workaround for doc/lit wrapper method # (you should consider to simply use rpc/lit service) # #unless soapaction # raise RPCRoutingError.new("soapaction is a must for document method") #end ensure_styleuse_option(opt, :document, :literal) op = ApplicationScopeOperation.new(soapaction, receiver, name, param_def, opt) if opt[:request_style] != :document raise RPCRoutingError.new("illegal request_style given") end assign_operation(soapaction, first_input_part_qname(param_def), op) end alias add_document_method add_document_operation def add_document_request_operation(factory, soapaction, name, param_def, opt = {}) # # adopt workaround for doc/lit wrapper method # (you should consider to simply use rpc/lit service) # #unless soapaction # raise RPCRoutingError.new("soapaction is a must for document method") #end ensure_styleuse_option(opt, :document, :literal) op = RequestScopeOperation.new(soapaction, receiver, name, param_def, opt) if opt[:request_style] != :document raise RPCRoutingError.new("illegal request_style given") end assign_operation(soapaction, first_input_part_qname(param_def), op) end def route(conn_data) # we cannot set request_default_encodingsyle before parsing the content. env = unmarshal(conn_data) if env.nil? raise ArgumentError.new("illegal SOAP marshal format") end op = lookup_operation(conn_data.soapaction, env.body) headerhandler = @headerhandler.dup @headerhandlerfactory.each do |f| headerhandler.add(f.create) end receive_headers(headerhandler, env.header) soap_response = default_encodingstyle = nil begin soap_response = op.call(env.body, @mapping_registry, @literal_mapping_registry, create_mapping_opt) default_encodingstyle = op.response_default_encodingstyle rescue Exception soap_response = fault($!) default_encodingstyle = nil end conn_data.is_fault = true if soap_response.is_a?(SOAPFault) header = call_headers(headerhandler) body = SOAPBody.new(soap_response) env = SOAPEnvelope.new(header, body) marshal(conn_data, env, default_encodingstyle) end # Create fault response string. def create_fault_response(e) env = SOAPEnvelope.new(SOAPHeader.new, SOAPBody.new(fault(e))) opt = {} opt[:external_content] = nil response_string = Processor.marshal(env, opt) conn_data = StreamHandler::ConnectionData.new(response_string) conn_data.is_fault = true if ext = opt[:external_content] mimeize(conn_data, ext) end conn_data end private def first_input_part_qname(param_def) param_def.each do |inout, paramname, typeinfo| if inout == SOAPMethod::IN klass, nsdef, namedef = typeinfo return XSD::QName.new(nsdef, namedef) end end nil end def create_styleuse_option(style, use) opt = {} opt[:request_style] = opt[:response_style] = style opt[:request_use] = opt[:response_use] = use opt end def ensure_styleuse_option(opt, style, use) opt[:request_style] ||= style opt[:response_style] ||= style opt[:request_use] ||= use opt[:response_use] ||= use end def assign_operation(soapaction, qname, op) assigned = false if soapaction and !soapaction.empty? @operation_by_soapaction[soapaction] = op assigned = true end if qname @operation_by_qname[qname] = op assigned = true end unless assigned raise RPCRoutingError.new("cannot assign operation") end end def lookup_operation(soapaction, body) if op = @operation_by_soapaction[soapaction] return op end qname = body.root_node.elename if op = @operation_by_qname[qname] return op end if soapaction raise RPCRoutingError.new( "operation: #{soapaction} #{qname} not supported") else raise RPCRoutingError.new("operation: #{qname} not supported") end end def call_headers(headerhandler) headers = headerhandler.on_outbound if headers.empty? nil else h = ::SOAP::SOAPHeader.new headers.each do |header| h.add(header.elename.name, header) end h end end def receive_headers(headerhandler, headers) headerhandler.on_inbound(headers) if headers end def unmarshal(conn_data) opt = {} contenttype = conn_data.receive_contenttype if /#{MIMEMessage::MultipartContentType}/i =~ contenttype opt[:external_content] = {} mime = MIMEMessage.parse("Content-Type: " + contenttype, conn_data.receive_string) mime.parts.each do |part| value = Attachment.new(part.content) value.contentid = part.contentid obj = SOAPAttachment.new(value) opt[:external_content][value.contentid] = obj if value.contentid end opt[:charset] = StreamHandler.parse_media_type(mime.root.headers['content-type'].str) env = Processor.unmarshal(mime.root.content, opt) else opt[:charset] = ::SOAP::StreamHandler.parse_media_type(contenttype) env = Processor.unmarshal(conn_data.receive_string, opt) end charset = opt[:charset] conn_data.send_contenttype = "text/xml; charset=\"#{charset}\"" env end def marshal(conn_data, env, default_encodingstyle = nil) opt = {} opt[:external_content] = nil opt[:default_encodingstyle] = default_encodingstyle opt[:generate_explicit_type] = @generate_explicit_type response_string = Processor.marshal(env, opt) conn_data.send_string = response_string if ext = opt[:external_content] mimeize(conn_data, ext) end conn_data end def mimeize(conn_data, ext) mime = MIMEMessage.new ext.each do |k, v| mime.add_attachment(v.data) end mime.add_part(conn_data.send_string + "\r\n") mime.close conn_data.send_string = mime.content_str conn_data.send_contenttype = mime.headers['content-type'].str conn_data end # Create fault response. def fault(e) detail = Mapping::SOAPException.new(e) SOAPFault.new( SOAPString.new('Server'), SOAPString.new(e.to_s), SOAPString.new(@actor), Mapping.obj2soap(detail, @mapping_registry)) end def create_mapping_opt { :external_ces => @external_ces } end class Operation attr_reader :name attr_reader :soapaction attr_reader :request_style attr_reader :response_style attr_reader :request_use attr_reader :response_use def initialize(soapaction, name, param_def, opt) @soapaction = soapaction @name = name @request_style = opt[:request_style] @response_style = opt[:response_style] @request_use = opt[:request_use] @response_use = opt[:response_use] check_style(@request_style) check_style(@response_style) check_use(@request_use) check_use(@response_use) if @response_style == :rpc request_qname = opt[:request_qname] or raise @rpc_method_factory = RPC::SOAPMethodRequest.new(request_qname, param_def, @soapaction) @rpc_response_qname = opt[:response_qname] else @doc_request_qnames = [] @doc_request_qualified = [] @doc_response_qnames = [] @doc_response_qualified = [] param_def.each do |inout, paramname, typeinfo, eleinfo| klass, nsdef, namedef = typeinfo qualified = eleinfo case inout when SOAPMethod::IN @doc_request_qnames << XSD::QName.new(nsdef, namedef) @doc_request_qualified << qualified when SOAPMethod::OUT @doc_response_qnames << XSD::QName.new(nsdef, namedef) @doc_response_qualified << qualified else raise ArgumentError.new( "illegal inout definition for document style: #{inout}") end end end end def request_default_encodingstyle (@request_use == :encoded) ? EncodingNamespace : LiteralNamespace end def response_default_encodingstyle (@response_use == :encoded) ? EncodingNamespace : LiteralNamespace end def call(body, mapping_registry, literal_mapping_registry, opt) if @request_style == :rpc values = request_rpc(body, mapping_registry, literal_mapping_registry, opt) else values = request_document(body, mapping_registry, literal_mapping_registry, opt) end result = receiver.method(@name.intern).call(*values) return result if result.is_a?(SOAPFault) if @response_style == :rpc response_rpc(result, mapping_registry, literal_mapping_registry, opt) else response_doc(result, mapping_registry, literal_mapping_registry, opt) end end private def receiver raise NotImplementedError.new('must be defined in derived class') end def request_rpc(body, mapping_registry, literal_mapping_registry, opt) request = body.request unless request.is_a?(SOAPStruct) raise RPCRoutingError.new("not an RPC style") end if @request_use == :encoded request_rpc_enc(request, mapping_registry, opt) else request_rpc_lit(request, literal_mapping_registry, opt) end end def request_document(body, mapping_registry, literal_mapping_registry, opt) # ToDo: compare names with @doc_request_qnames if @request_use == :encoded request_doc_enc(body, mapping_registry, opt) else request_doc_lit(body, literal_mapping_registry, opt) end end def request_rpc_enc(request, mapping_registry, opt) param = Mapping.soap2obj(request, mapping_registry, nil, opt) request.collect { |key, value| param[key] } end def request_rpc_lit(request, mapping_registry, opt) request.collect { |key, value| Mapping.soap2obj(value, mapping_registry, nil, opt) } end def request_doc_enc(body, mapping_registry, opt) body.collect { |key, value| Mapping.soap2obj(value, mapping_registry, nil, opt) } end def request_doc_lit(body, mapping_registry, opt) body.collect { |key, value| Mapping.soap2obj(value, mapping_registry, nil, opt) } end def response_rpc(result, mapping_registry, literal_mapping_registry, opt) if @response_use == :encoded response_rpc_enc(result, mapping_registry, opt) else response_rpc_lit(result, literal_mapping_registry, opt) end end def response_doc(result, mapping_registry, literal_mapping_registry, opt) if @doc_response_qnames.size == 1 and !result.is_a?(Array) result = [result] end if result.size != @doc_response_qnames.size raise "required #{@doc_response_qnames.size} responses " + "but #{result.size} given" end if @response_use == :encoded response_doc_enc(result, mapping_registry, opt) else response_doc_lit(result, literal_mapping_registry, opt) end end def response_rpc_enc(result, mapping_registry, opt) soap_response = @rpc_method_factory.create_method_response(@rpc_response_qname) if soap_response.have_outparam? unless result.is_a?(Array) raise RPCRoutingError.new("out parameter was not returned") end outparams = {} i = 1 soap_response.output_params.each do |outparam| outparams[outparam] = Mapping.obj2soap(result[i], mapping_registry, nil, opt) i += 1 end soap_response.set_outparam(outparams) soap_response.retval = Mapping.obj2soap(result[0], mapping_registry, nil, opt) else soap_response.retval = Mapping.obj2soap(result, mapping_registry, nil, opt) end soap_response end def response_rpc_lit(result, mapping_registry, opt) soap_response = @rpc_method_factory.create_method_response(@rpc_response_qname) if soap_response.have_outparam? unless result.is_a?(Array) raise RPCRoutingError.new("out parameter was not returned") end outparams = {} i = 1 soap_response.output_params.each do |outparam| outparams[outparam] = Mapping.obj2soap(result[i], mapping_registry, XSD::QName.new(nil, outparam), opt) i += 1 end soap_response.set_outparam(outparams) soap_response.retval = Mapping.obj2soap(result[0], mapping_registry, XSD::QName.new(nil, soap_response.elename), opt) else soap_response.retval = Mapping.obj2soap(result, mapping_registry, XSD::QName.new(nil, soap_response.elename), opt) end soap_response end def response_doc_enc(result, mapping_registry, opt) (0...result.size).collect { |idx| ele = Mapping.obj2soap(result[idx], mapping_registry, nil, opt) ele.elename = @doc_response_qnames[idx] ele } end def response_doc_lit(result, mapping_registry, opt) (0...result.size).collect { |idx| ele = Mapping.obj2soap(result[idx], mapping_registry, @doc_response_qnames[idx]) ele.encodingstyle = LiteralNamespace if ele.respond_to?(:qualified) ele.qualified = @doc_response_qualified[idx] end ele } end def check_style(style) unless [:rpc, :document].include?(style) raise ArgumentError.new("unknown style: #{style}") end end def check_use(use) unless [:encoded, :literal].include?(use) raise ArgumentError.new("unknown use: #{use}") end end end class ApplicationScopeOperation < Operation def initialize(soapaction, receiver, name, param_def, opt) super(soapaction, name, param_def, opt) @receiver = receiver end private def receiver @receiver end end class RequestScopeOperation < Operation def initialize(soapaction, receiver_factory, name, param_def, opt) super(soapaction, name, param_def, opt) unless receiver_factory.respond_to?(:create) raise TypeError.new("factory must respond to 'create'") end @receiver_factory = receiver_factory end private def receiver @receiver_factory.create 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/soap/rpc/soaplet.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/rpc/soaplet.rb
# SOAP4R - SOAP handler servlet for WEBrick # Copyright (C) 2001-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 'webrick/httpservlet/abstract' require 'webrick/httpstatus' require 'soap/rpc/router' require 'soap/streamHandler' begin require 'stringio' require 'zlib' rescue LoadError warn("Loading stringio or zlib failed. No gzipped response supported.") if $DEBUG end warn("Overriding WEBrick::Log#debug") if $DEBUG require 'webrick/log' module WEBrick class Log < BasicLog alias __debug debug def debug(msg = nil) if block_given? and msg.nil? __debug(yield) else __debug(msg) end end end end module SOAP module RPC class SOAPlet < WEBrick::HTTPServlet::AbstractServlet public attr_reader :options def initialize(router = nil) @router = router || ::SOAP::RPC::Router.new(self.class.name) @options = {} @config = {} end # for backward compatibility def app_scope_router @router end # for backward compatibility def add_servant(obj, namespace) @router.add_rpc_servant(obj, namespace) end def allow_content_encoding_gzip=(allow) @options[:allow_content_encoding_gzip] = allow end ### ## Servlet interfaces for WEBrick. # def get_instance(config, *options) @config = config self end def require_path_info? false end def do_GET(req, res) res.header['Allow'] = 'POST' raise WEBrick::HTTPStatus::MethodNotAllowed, "GET request not allowed" end def do_POST(req, res) logger.debug { "SOAP request: " + req.body } if logger begin conn_data = ::SOAP::StreamHandler::ConnectionData.new setup_req(conn_data, req) @router.external_ces = @options[:external_ces] conn_data = @router.route(conn_data) setup_res(conn_data, req, res) rescue Exception => e conn_data = @router.create_fault_response(e) res.status = WEBrick::HTTPStatus::RC_INTERNAL_SERVER_ERROR res.body = conn_data.send_string res['content-type'] = conn_data.send_contenttype || "text/xml" end if res.body.is_a?(IO) res.chunked = true logger.debug { "SOAP response: (chunked response not logged)" } if logger else logger.debug { "SOAP response: " + res.body } if logger end end private def logger @config[:Logger] end def setup_req(conn_data, req) conn_data.receive_string = req.body conn_data.receive_contenttype = req['content-type'] conn_data.soapaction = parse_soapaction(req.meta_vars['HTTP_SOAPACTION']) end def setup_res(conn_data, req, res) res['content-type'] = conn_data.send_contenttype if conn_data.is_fault res.status = WEBrick::HTTPStatus::RC_INTERNAL_SERVER_ERROR end if outstring = encode_gzip(req, conn_data.send_string) res['content-encoding'] = 'gzip' res['content-length'] = outstring.size res.body = outstring else res.body = conn_data.send_string end end def parse_soapaction(soapaction) if !soapaction.nil? and !soapaction.empty? if /^"(.+)"$/ =~ soapaction return $1 end end nil end def encode_gzip(req, outstring) unless encode_gzip?(req) return nil end begin ostream = StringIO.new gz = Zlib::GzipWriter.new(ostream) gz.write(outstring) ostream.string ensure gz.close end end def encode_gzip?(req) @options[:allow_content_encoding_gzip] and defined?(::Zlib) and req['accept-encoding'] and req['accept-encoding'].split(/,\s*/).include?('gzip') 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/rpc/cgistub.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/rpc/cgistub.rb
# SOAP4R - CGI/mod_ruby stub 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. require 'soap/streamHandler' require 'webrick/httpresponse' require 'webrick/httpstatus' require 'logger' require 'soap/rpc/soaplet' module SOAP module RPC ### # SYNOPSIS # CGIStub.new # # DESCRIPTION # To be written... # class CGIStub < Logger::Application include SOAP include WEBrick class SOAPRequest attr_reader :body def [](var); end def meta_vars; end end class SOAPStdinRequest < SOAPRequest attr_reader :body def initialize(stream) size = ENV['CONTENT_LENGTH'].to_i || 0 @body = stream.read(size) end def [](var) ENV[var.gsub(/-/, '_').upcase] end def meta_vars { 'HTTP_SOAPACTION' => ENV['HTTP_SOAPAction'] } end end class SOAPFCGIRequest < SOAPRequest attr_reader :body def initialize(request) @request = request @body = @request.in.read end def [](var) @request.env[var.gsub(/-/, '_').upcase] end def meta_vars { 'HTTP_SOAPACTION' => @request.env['HTTP_SOAPAction'] } end end def initialize(appname, default_namespace) super(appname) set_log(STDERR) self.level = ERROR @default_namespace = default_namespace @remote_host = ENV['REMOTE_HOST'] || ENV['REMOTE_ADDR'] || 'unknown' @router = ::SOAP::RPC::Router.new(self.class.name) @soaplet = ::SOAP::RPC::SOAPlet.new(@router) on_init end def on_init # do extra initialization in a derived class if needed. end def mapping_registry @router.mapping_registry end def mapping_registry=(value) @router.mapping_registry = value end def generate_explicit_type @router.generate_explicit_type end def generate_explicit_type=(generate_explicit_type) @router.generate_explicit_type = generate_explicit_type end # servant entry interface def add_rpc_servant(obj, namespace = @default_namespace) @router.add_rpc_servant(obj, namespace) end alias add_servant add_rpc_servant def add_headerhandler(obj) @router.add_headerhandler(obj) end alias add_rpc_headerhandler add_headerhandler # method entry interface def add_rpc_method(obj, name, *param) add_rpc_method_with_namespace_as(@default_namespace, obj, name, name, *param) end alias add_method add_rpc_method def add_rpc_method_as(obj, name, name_as, *param) add_rpc_method_with_namespace_as(@default_namespace, obj, name, name_as, *param) end alias add_method_as add_rpc_method_as def add_rpc_method_with_namespace(namespace, obj, name, *param) add_rpc_method_with_namespace_as(namespace, obj, name, name, *param) end alias add_method_with_namespace add_rpc_method_with_namespace def add_rpc_method_with_namespace_as(namespace, obj, name, name_as, *param) qname = XSD::QName.new(namespace, name_as) soapaction = nil param_def = SOAPMethod.derive_rpc_param_def(obj, name, *param) @router.add_rpc_operation(obj, qname, soapaction, name, param_def) end alias add_method_with_namespace_as add_rpc_method_with_namespace_as def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {}) @router.add_rpc_operation(receiver, qname, soapaction, name, param_def, opt) end def add_document_operation(receiver, soapaction, name, param_def, opt = {}) @router.add_document_operation(receiver, soapaction, name, param_def, opt) end def set_fcgi_request(request) @fcgi = request end private HTTPVersion = WEBrick::HTTPVersion.new('1.0') # dummy; ignored def run res = WEBrick::HTTPResponse.new({:HTTPVersion => HTTPVersion}) begin @log.info { "received a request from '#{ @remote_host }'" } if @fcgi req = SOAPFCGIRequest.new(@fcgi) else req = SOAPStdinRequest.new($stdin) end @soaplet.do_POST(req, res) rescue HTTPStatus::EOFError, HTTPStatus::RequestTimeout => ex res.set_error(ex) rescue HTTPStatus::Error => ex res.set_error(ex) rescue HTTPStatus::Status => ex res.status = ex.code rescue StandardError, NameError => ex # for Ruby 1.6 res.set_error(ex, true) ensure if defined?(MOD_RUBY) r = Apache.request r.status = res.status r.content_type = res.content_type r.send_http_header buf = res.body else buf = '' res.send_response(buf) buf.sub!(/^[^\r]+\r\n/, '') # Trim status line. end @log.debug { "SOAP CGI Response:\n#{ buf }" } if @fcgi @fcgi.out.print buf @fcgi.finish @fcgi = nil else print buf end end 0 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/rpc/httpserver.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/rpc/httpserver.rb
# SOAP4R - WEBrick HTTP Server # Copyright (C) 2003, 2004 by 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 'soap/rpc/soaplet' require 'soap/streamHandler' require 'webrick' module SOAP module RPC class HTTPServer < Logger::Application attr_reader :server attr_accessor :default_namespace def initialize(config) super(config[:SOAPHTTPServerApplicationName] || self.class.name) @default_namespace = config[:SOAPDefaultNamespace] @webrick_config = config.dup self.level = Logger::Severity::ERROR # keep silent by default @webrick_config[:Logger] ||= @log @log = @webrick_config[:Logger] # sync logger of App and HTTPServer @router = ::SOAP::RPC::Router.new(self.class.name) @soaplet = ::SOAP::RPC::SOAPlet.new(@router) on_init @server = WEBrick::HTTPServer.new(@webrick_config) @server.mount('/', @soaplet) end def on_init # do extra initialization in a derived class if needed. end def status @server.status if @server end def shutdown @server.shutdown if @server end def mapping_registry @router.mapping_registry end def mapping_registry=(mapping_registry) @router.mapping_registry = mapping_registry end def generate_explicit_type @router.generate_explicit_type end def generate_explicit_type=(generate_explicit_type) @router.generate_explicit_type = generate_explicit_type end # servant entry interface def add_rpc_request_servant(factory, namespace = @default_namespace) @router.add_rpc_request_servant(factory, namespace) end def add_rpc_servant(obj, namespace = @default_namespace) @router.add_rpc_servant(obj, namespace) end def add_request_headerhandler(factory) @router.add_request_headerhandler(factory) end def add_headerhandler(obj) @router.add_headerhandler(obj) end alias add_rpc_headerhandler add_headerhandler # method entry interface def add_rpc_method(obj, name, *param) add_rpc_method_as(obj, name, name, *param) end alias add_method add_rpc_method def add_rpc_method_as(obj, name, name_as, *param) qname = XSD::QName.new(@default_namespace, name_as) soapaction = nil param_def = SOAPMethod.derive_rpc_param_def(obj, name, *param) @router.add_rpc_operation(obj, qname, soapaction, name, param_def) end alias add_method_as add_rpc_method_as def add_document_method(obj, soapaction, name, req_qnames, res_qnames) param_def = SOAPMethod.create_doc_param_def(req_qnames, res_qnames) @router.add_document_operation(obj, soapaction, name, param_def) end def add_rpc_operation(receiver, qname, soapaction, name, param_def, opt = {}) @router.add_rpc_operation(receiver, qname, soapaction, name, param_def, opt) end def add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt = {}) @router.add_rpc_request_operation(factory, qname, soapaction, name, param_def, opt) end def add_document_operation(receiver, soapaction, name, param_def, opt = {}) @router.add_document_operation(receiver, soapaction, name, param_def, opt) end def add_document_request_operation(factory, soapaction, name, param_def, opt = {}) @router.add_document_request_operation(factory, soapaction, name, param_def, opt) end private def run @server.start 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/encodingstyle/aspDotNetHandler.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/encodingstyle/aspDotNetHandler.rb
# SOAP4R - ASP.NET EncodingStyle handler 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. require 'soap/encodingstyle/handler' module SOAP module EncodingStyle class ASPDotNetHandler < Handler Namespace = 'http://tempuri.org/ASP.NET' add_handler def initialize(charset = nil) super(charset) @textbuf = '' @decode_typemap = nil end ### ## encode interface. # def encode_data(generator, ns, data, parent) attrs = {} # ASPDotNetHandler is intended to be used for accessing an ASP.NET doc/lit # service as an rpc/encoded service. in the situation, local elements # should be qualified. propagate parent's namespace to children. if data.elename.namespace.nil? data.elename.namespace = parent.elename.namespace end name = generator.encode_name(ns, data, attrs) case data when SOAPRawString generator.encode_tag(name, attrs) generator.encode_rawstring(data.to_s) when XSD::XSDString generator.encode_tag(name, attrs) generator.encode_string(@charset ? XSD::Charset.encoding_to_xml(data.to_s, @charset) : data.to_s) when XSD::XSDAnySimpleType generator.encode_tag(name, attrs) generator.encode_string(data.to_s) when SOAPStruct generator.encode_tag(name, attrs) data.each do |key, value| generator.encode_child(ns, value, data) end when SOAPArray generator.encode_tag(name, attrs) data.traverse do |child, *rank| data.position = nil generator.encode_child(ns, child, data) end else raise EncodingStyleError.new( "unknown object:#{data} in this encodingStyle") end end def encode_data_end(generator, ns, data, parent) name = generator.encode_name_end(ns, data) cr = data.is_a?(SOAPCompoundtype) generator.encode_tag_end(name, cr) end ### ## decode interface. # class SOAPTemporalObject attr_accessor :parent def initialize @parent = nil end end class SOAPUnknown < SOAPTemporalObject def initialize(handler, elename) super() @handler = handler @elename = elename end def as_struct o = SOAPStruct.decode(@elename, XSD::AnyTypeName) o.parent = @parent o.type.name = @name @handler.decode_parent(@parent, o) o end def as_string o = SOAPString.decode(@elename) o.parent = @parent @handler.decode_parent(@parent, o) o end def as_nil o = SOAPNil.decode(@elename) o.parent = @parent @handler.decode_parent(@parent, o) o end end def decode_tag(ns, elename, attrs, parent) @textbuf = '' o = SOAPUnknown.new(self, elename) o.parent = parent o end def decode_tag_end(ns, node) o = node.node if o.is_a?(SOAPUnknown) newnode = o.as_string # if /\A\s*\z/ =~ @textbuf # o.as_struct # else # o.as_string # end node.replace_node(newnode) o = node.node end decode_textbuf(o) @textbuf = '' end def decode_text(ns, text) # @textbuf is set at decode_tag_end. @textbuf << text end def decode_prologue end def decode_epilogue end def decode_parent(parent, node) case parent.node when SOAPUnknown newparent = parent.node.as_struct node.parent = newparent parent.replace_node(newparent) decode_parent(parent, node) when SOAPStruct data = parent.node[node.elename.name] case data when nil parent.node.add(node.elename.name, node) when SOAPArray name, type_ns = node.elename.name, node.type.namespace data.add(node) node.elename, node.type.namespace = name, type_ns else parent.node[node.elename.name] = SOAPArray.new name, type_ns = data.elename.name, data.type.namespace parent.node[node.elename.name].add(data) data.elename.name, data.type.namespace = name, type_ns name, type_ns = node.elename.name, node.type.namespace parent.node[node.elename.name].add(node) node.elename.name, node.type.namespace = name, type_ns end when SOAPArray if node.position parent.node[*(decode_arypos(node.position))] = node parent.node.sparse = true else parent.node.add(node) end when SOAPBasetype raise EncodingStyleError.new("SOAP base type must not have a child") else # SOAPUnknown does not have parent. # raise EncodingStyleError.new("illegal parent: #{parent}") end end private def decode_textbuf(node) if node.is_a?(XSD::XSDString) if @charset node.set(XSD::Charset.encoding_from_xml(@textbuf, @charset)) else node.set(@textbuf) end else # Nothing to do... end end end ASPDotNetHandler.new 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/encodingstyle/handler.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/encodingstyle/handler.rb
# SOAP4R - EncodingStyle handler 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 'soap/soap' require 'soap/baseData' require 'soap/element' module SOAP module EncodingStyle class Handler @@handlers = {} class EncodingStyleError < Error; end class << self def uri self::Namespace end def handler(uri) @@handlers[uri] end def each @@handlers.each do |key, value| yield(value) end end private def add_handler @@handlers[self.uri] = self end end attr_reader :charset attr_accessor :generate_explicit_type def decode_typemap=(definedtypes) @decode_typemap = definedtypes end def initialize(charset) @charset = charset @generate_explicit_type = true @decode_typemap = nil end ### ## encode interface. # # Returns a XML instance as a string. def encode_data(generator, ns, data, parent) raise NotImplementError end def encode_data_end(generator, ns, data, parent) raise NotImplementError end def encode_prologue end def encode_epilogue end ### ## decode interface. # # Returns SOAP/OM data. def decode_tag(ns, name, attrs, parent) raise NotImplementError.new('Method decode_tag must be defined in derived class.') end def decode_tag_end(ns, name) raise NotImplementError.new('Method decode_tag_end must be defined in derived class.') end def decode_text(ns, text) raise NotImplementError.new('Method decode_text must be defined in derived class.') end def decode_prologue end def decode_epilogue 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/encodingstyle/soapHandler.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/encodingstyle/soapHandler.rb
# SOAP4R - SOAP EncodingStyle handler 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. require 'soap/encodingstyle/handler' module SOAP module EncodingStyle class SOAPHandler < Handler Namespace = SOAP::EncodingNamespace add_handler def initialize(charset = nil) super(charset) @refpool = [] @idpool = [] @textbuf = '' @is_first_top_ele = true end ### ## encode interface. # def encode_data(generator, ns, data, parent) attrs = encode_attrs(generator, ns, data, parent) if parent && parent.is_a?(SOAPArray) && parent.position attrs[ns.name(AttrPositionName)] = "[#{parent.position.join(',')}]" end name = generator.encode_name(ns, data, attrs) case data when SOAPReference attrs['href'] = data.refidstr generator.encode_tag(name, attrs) when SOAPExternalReference data.referred attrs['href'] = data.refidstr generator.encode_tag(name, attrs) when SOAPRawString generator.encode_tag(name, attrs) generator.encode_rawstring(data.to_s) when XSD::XSDString generator.encode_tag(name, attrs) generator.encode_string(@charset ? XSD::Charset.encoding_to_xml(data.to_s, @charset) : data.to_s) when XSD::XSDAnySimpleType generator.encode_tag(name, attrs) generator.encode_string(data.to_s) when SOAPStruct generator.encode_tag(name, attrs) data.each do |key, value| generator.encode_child(ns, value, data) end when SOAPArray generator.encode_tag(name, attrs) data.traverse do |child, *rank| data.position = data.sparse ? rank : nil generator.encode_child(ns, child, data) end else raise EncodingStyleError.new( "unknown object:#{data} in this encodingStyle") end end def encode_data_end(generator, ns, data, parent) name = generator.encode_name_end(ns, data) cr = data.is_a?(SOAPCompoundtype) generator.encode_tag_end(name, cr) end ### ## decode interface. # class SOAPTemporalObject attr_accessor :parent attr_accessor :position attr_accessor :id attr_accessor :root def initialize @parent = nil @position = nil @id = nil @root = nil end end class SOAPUnknown < SOAPTemporalObject attr_reader :type attr_accessor :definedtype attr_reader :extraattr def initialize(handler, elename, type, extraattr) super() @handler = handler @elename = elename @type = type @extraattr = extraattr @definedtype = nil end def as_struct o = SOAPStruct.decode(@elename, @type) o.id = @id o.root = @root o.parent = @parent o.position = @position o.extraattr.update(@extraattr) @handler.decode_parent(@parent, o) o end def as_string o = SOAPString.decode(@elename) o.id = @id o.root = @root o.parent = @parent o.position = @position o.extraattr.update(@extraattr) @handler.decode_parent(@parent, o) o end def as_nil o = SOAPNil.decode(@elename) o.id = @id o.root = @root o.parent = @parent o.position = @position o.extraattr.update(@extraattr) @handler.decode_parent(@parent, o) o end end def decode_tag(ns, elename, attrs, parent) @textbuf = '' is_nil, type, arytype, root, offset, position, href, id, extraattr = decode_attrs(ns, attrs) o = nil if is_nil o = SOAPNil.decode(elename) elsif href o = SOAPReference.decode(elename, href) @refpool << o elsif @decode_typemap o = decode_tag_by_wsdl(ns, elename, type, parent.node, arytype, extraattr) else o = decode_tag_by_type(ns, elename, type, parent.node, arytype, extraattr) end if o.is_a?(SOAPArray) if offset o.offset = decode_arypos(offset) o.sparse = true else o.sparse = false end end o.parent = parent o.id = id o.root = root o.position = position unless o.is_a?(SOAPTemporalObject) @idpool << o if o.id decode_parent(parent, o) end o end def decode_tag_end(ns, node) o = node.node if o.is_a?(SOAPUnknown) newnode = if /\A\s*\z/ =~ @textbuf o.as_struct else o.as_string end if newnode.id @idpool << newnode end node.replace_node(newnode) o = node.node end decode_textbuf(o) # unlink definedtype o.definedtype = nil end def decode_text(ns, text) @textbuf << text end def decode_prologue @refpool.clear @idpool.clear @is_first_top_ele = true end def decode_epilogue decode_resolve_id end def decode_parent(parent, node) return unless parent.node case parent.node when SOAPUnknown newparent = parent.node.as_struct node.parent = newparent if newparent.id @idpool << newparent end parent.replace_node(newparent) decode_parent(parent, node) when SOAPStruct parent.node.add(node.elename.name, node) node.parent = parent.node when SOAPArray if node.position parent.node[*(decode_arypos(node.position))] = node parent.node.sparse = true else parent.node.add(node) end node.parent = parent.node else raise EncodingStyleError.new("illegal parent: #{parent.node}") end end private def content_ranksize(typename) typename.scan(/\[[\d,]*\]$/)[0] end def content_typename(typename) typename.sub(/\[,*\]$/, '') end def create_arytype(ns, data) XSD::QName.new(data.arytype.namespace, content_typename(data.arytype.name) + "[#{data.size.join(',')}]") end def encode_attrs(generator, ns, data, parent) attrs = {} return attrs if data.is_a?(SOAPReference) if !parent || parent.encodingstyle != EncodingNamespace if @generate_explicit_type SOAPGenerator.assign_ns(attrs, ns, EnvelopeNamespace) attrs[ns.name(AttrEncodingStyleName)] = EncodingNamespace end data.encodingstyle = EncodingNamespace end if data.is_a?(SOAPNil) attrs[ns.name(XSD::AttrNilName)] = XSD::NilValue elsif @generate_explicit_type if data.type.namespace SOAPGenerator.assign_ns(attrs, ns, data.type.namespace) end if data.is_a?(SOAPArray) if data.arytype.namespace SOAPGenerator.assign_ns(attrs, ns, data.arytype.namespace) end SOAPGenerator.assign_ns(attrs, ns, EncodingNamespace) attrs[ns.name(AttrArrayTypeName)] = ns.name(create_arytype(ns, data)) if data.type.name attrs[ns.name(XSD::AttrTypeName)] = ns.name(data.type) end elsif parent && parent.is_a?(SOAPArray) && (parent.arytype == data.type) # No need to add. elsif !data.type.namespace # No need to add. else attrs[ns.name(XSD::AttrTypeName)] = ns.name(data.type) end end data.extraattr.each do |key, value| SOAPGenerator.assign_ns(attrs, ns, key.namespace) attrs[ns.name(key)] = encode_attr_value(generator, ns, key, value) end if data.id attrs['id'] = data.id end attrs end def encode_attr_value(generator, ns, qname, value) if value.is_a?(SOAPType) ref = SOAPReference.new(value) generator.add_reftarget(qname.name, value) ref.refidstr else value.to_s end end def decode_tag_by_wsdl(ns, elename, typestr, parent, arytypestr, extraattr) o = nil if parent.class == SOAPBody # root element: should branch by root attribute? if @is_first_top_ele # Unqualified name is allowed here. @is_first_top_ele = false type = @decode_typemap[elename] || @decode_typemap.find_name(elename.name) if type o = SOAPStruct.new(elename) o.definedtype = type return o end end # multi-ref element. if typestr typename = ns.parse(typestr) typedef = @decode_typemap[typename] if typedef return decode_definedtype(elename, typename, typedef, arytypestr) end end return decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) end if parent.type == XSD::AnyTypeName return decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) end # parent.definedtype == nil means the parent is SOAPUnknown. SOAPUnknown # is generated by decode_tag_by_type when its type is anyType. parenttype = parent.definedtype || @decode_typemap[parent.type] unless parenttype return decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) end definedtype_name = parenttype.child_type(elename) if definedtype_name and (klass = TypeMap[definedtype_name]) return decode_basetype(klass, elename) elsif definedtype_name == XSD::AnyTypeName return decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) end if definedtype_name typedef = @decode_typemap[definedtype_name] else typedef = parenttype.child_defined_complextype(elename) end decode_definedtype(elename, definedtype_name, typedef, arytypestr) end def decode_definedtype(elename, typename, typedef, arytypestr) unless typedef raise EncodingStyleError.new("unknown type '#{typename}'") end if typedef.is_a?(::WSDL::XMLSchema::SimpleType) decode_defined_simpletype(elename, typename, typedef, arytypestr) else decode_defined_complextype(elename, typename, typedef, arytypestr) end end def decode_basetype(klass, elename) klass.decode(elename) end def decode_defined_simpletype(elename, typename, typedef, arytypestr) o = decode_basetype(TypeMap[typedef.base], elename) o.definedtype = typedef o end def decode_defined_complextype(elename, typename, typedef, arytypestr) case typedef.compoundtype when :TYPE_STRUCT, :TYPE_MAP o = SOAPStruct.decode(elename, typename) o.definedtype = typedef return o when :TYPE_ARRAY expected_arytype = typedef.find_arytype if arytypestr actual_arytype = XSD::QName.new(expected_arytype.namespace, content_typename(expected_arytype.name) << content_ranksize(arytypestr)) o = SOAPArray.decode(elename, typename, actual_arytype) else o = SOAPArray.new(typename, 1, expected_arytype) o.elename = elename end o.definedtype = typedef return o when :TYPE_EMPTY o = SOAPNil.decode(elename) o.definedtype = typedef return o else raise RuntimeError.new( "Unknown kind of complexType: #{typedef.compoundtype}") end nil end def decode_tag_by_type(ns, elename, typestr, parent, arytypestr, extraattr) if arytypestr type = typestr ? ns.parse(typestr) : ValueArrayName node = SOAPArray.decode(elename, type, ns.parse(arytypestr)) node.extraattr.update(extraattr) return node end type = nil if typestr type = ns.parse(typestr) elsif parent.is_a?(SOAPArray) type = parent.arytype else # Since it's in dynamic(without any type) encoding process, # assumes entity as its type itself. # <SOAP-ENC:Array ...> => type Array in SOAP-ENC. # <Country xmlns="foo"> => type Country in foo. type = elename end if (klass = TypeMap[type]) node = decode_basetype(klass, elename) node.extraattr.update(extraattr) return node end # Unknown type... Struct or String SOAPUnknown.new(self, elename, type, extraattr) end def decode_textbuf(node) case node when XSD::XSDHexBinary, XSD::XSDBase64Binary node.set_encoded(@textbuf) when XSD::XSDString if @charset @textbuf = XSD::Charset.encoding_from_xml(@textbuf, @charset) end if node.definedtype node.definedtype.check_lexical_format(@textbuf) end node.set(@textbuf) when SOAPNil # Nothing to do. when SOAPBasetype node.set(@textbuf) else # Nothing to do... end @textbuf = '' end NilLiteralMap = { 'true' => true, '1' => true, 'false' => false, '0' => false } RootLiteralMap = { '1' => 1, '0' => 0 } def decode_attrs(ns, attrs) is_nil = false type = nil arytype = nil root = nil offset = nil position = nil href = nil id = nil extraattr = {} attrs.each do |key, value| qname = ns.parse(key) case qname.namespace when XSD::InstanceNamespace case qname.name when XSD::NilLiteral is_nil = NilLiteralMap[value] or raise EncodingStyleError.new("cannot accept attribute value: #{value} as the value of xsi:#{XSD::NilLiteral} (expected 'true', 'false', '1', or '0')") next when XSD::AttrType type = value next end when EncodingNamespace case qname.name when AttrArrayType arytype = value next when AttrRoot root = RootLiteralMap[value] or raise EncodingStyleError.new( "illegal root attribute value: #{value}") next when AttrOffset offset = value next when AttrPosition position = value next end end if key == 'href' href = value next elsif key == 'id' id = value next end qname = ns.parse_local(key) extraattr[qname] = decode_attr_value(ns, qname, value) end return is_nil, type, arytype, root, offset, position, href, id, extraattr end def decode_attr_value(ns, qname, value) if /\A#/ =~ value o = SOAPReference.decode(nil, value) @refpool << o o else value end end def decode_arypos(position) /^\[(.+)\]$/ =~ position $1.split(',').collect { |s| s.to_i } end def decode_resolve_id count = @refpool.length # To avoid infinite loop while !@refpool.empty? && count > 0 @refpool = @refpool.find_all { |ref| o = @idpool.find { |item| item.id == ref.refid } if o.is_a?(SOAPReference) true # link of link. elsif o ref.__setobj__(o) false elsif o = ref.rootnode.external_content[ref.refid] ref.__setobj__(o) false else raise EncodingStyleError.new("unresolved reference: #{ref.refid}") end } count -= 1 end end end SOAPHandler.new 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/encodingstyle/literalHandler.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/encodingstyle/literalHandler.rb
# SOAP4R - XML Literal EncodingStyle handler 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. require 'soap/encodingstyle/handler' module SOAP module EncodingStyle class LiteralHandler < Handler Namespace = SOAP::LiteralNamespace add_handler def initialize(charset = nil) super(charset) @textbuf = '' end ### ## encode interface. # def encode_data(generator, ns, data, parent) attrs = {} name = generator.encode_name(ns, data, attrs) data.extraattr.each do |k, v| # ToDo: check generator.attributeformdefault here if k.is_a?(XSD::QName) if k.namespace SOAPGenerator.assign_ns(attrs, ns, k.namespace) k = ns.name(k) else k = k.name end end attrs[k] = v end case data when SOAPRawString generator.encode_tag(name, attrs) generator.encode_rawstring(data.to_s) when XSD::XSDString generator.encode_tag(name, attrs) str = data.to_s str = XSD::Charset.encoding_to_xml(str, @charset) if @charset generator.encode_string(str) when XSD::XSDAnySimpleType generator.encode_tag(name, attrs) generator.encode_string(data.to_s) when SOAPStruct generator.encode_tag(name, attrs) data.each do |key, value| generator.encode_child(ns, value, data) end when SOAPArray generator.encode_tag(name, attrs) data.traverse do |child, *rank| data.position = nil generator.encode_child(ns, child, data) end when SOAPElement # passes 2 times for simplifying namespace definition data.each do |key, value| if value.elename.namespace SOAPGenerator.assign_ns(attrs, ns, value.elename.namespace) end end generator.encode_tag(name, attrs) generator.encode_rawstring(data.text) if data.text data.each do |key, value| generator.encode_child(ns, value, data) end else raise EncodingStyleError.new( "unknown object:#{data} in this encodingStyle") end end def encode_data_end(generator, ns, data, parent) name = generator.encode_name_end(ns, data) cr = (data.is_a?(SOAPCompoundtype) or (data.is_a?(SOAPElement) and !data.text)) generator.encode_tag_end(name, cr) end ### ## decode interface. # class SOAPTemporalObject attr_accessor :parent def initialize @parent = nil end end class SOAPUnknown < SOAPTemporalObject def initialize(handler, elename, extraattr) super() @handler = handler @elename = elename @extraattr = extraattr end def as_element o = SOAPElement.decode(@elename) o.parent = @parent o.extraattr.update(@extraattr) @handler.decode_parent(@parent, o) o end def as_string o = SOAPString.decode(@elename) o.parent = @parent o.extraattr.update(@extraattr) @handler.decode_parent(@parent, o) o end def as_nil o = SOAPNil.decode(@elename) o.parent = @parent o.extraattr.update(@extraattr) @handler.decode_parent(@parent, o) o end end def decode_tag(ns, elename, attrs, parent) @textbuf = '' o = SOAPUnknown.new(self, elename, decode_attrs(ns, attrs)) o.parent = parent o end def decode_tag_end(ns, node) o = node.node if o.is_a?(SOAPUnknown) newnode = if /\A\s*\z/ =~ @textbuf o.as_element else o.as_string end node.replace_node(newnode) o = node.node end decode_textbuf(o) @textbuf = '' end def decode_text(ns, text) # @textbuf is set at decode_tag_end. @textbuf << text end def decode_attrs(ns, attrs) extraattr = {} attrs.each do |key, value| qname = ns.parse_local(key) extraattr[qname] = value end extraattr end def decode_prologue end def decode_epilogue end def decode_parent(parent, node) return unless parent.node case parent.node when SOAPUnknown newparent = parent.node.as_element node.parent = newparent parent.replace_node(newparent) decode_parent(parent, node) when SOAPElement parent.node.add(node) node.parent = parent.node when SOAPStruct parent.node.add(node.elename.name, node) node.parent = parent.node when SOAPArray if node.position parent.node[*(decode_arypos(node.position))] = node parent.node.sparse = true else parent.node.add(node) end node.parent = parent.node else raise EncodingStyleError.new("illegal parent: #{parent.node}") end end private def decode_textbuf(node) if node.is_a?(XSD::XSDString) if @charset node.set(XSD::Charset.encoding_from_xml(@textbuf, @charset)) else node.set(@textbuf) end else # Nothing to do... end end end LiteralHandler.new 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/header/handlerset.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/header/handlerset.rb
# SOAP4R - SOAP Header handler set # Copyright (C) 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 'xsd/namedelements' module SOAP module Header class HandlerSet def initialize @store = XSD::NamedElements.new end def dup obj = HandlerSet.new obj.store = @store.dup obj end def add(handler) @store << handler end alias << add def delete(handler) @store.delete(handler) end def include?(handler) @store.include?(handler) end # returns: Array of SOAPHeaderItem def on_outbound @store.collect { |handler| handler.on_outbound_headeritem }.compact end # headers: SOAPHeaderItem enumerable object def on_inbound(headers) headers.each do |name, item| handler = @store.find { |handler| handler.elename == item.element.elename } if handler handler.on_inbound_headeritem(item) elsif item.mustunderstand raise UnhandledMustUnderstandHeaderError.new(item.element.elename.to_s) end end end protected def store=(store) @store = store 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/header/simplehandler.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/header/simplehandler.rb
# SOAP4R - SOAP Simple header item handler # 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/header/handler' require 'soap/baseData' module SOAP module Header class SimpleHandler < SOAP::Header::Handler def initialize(elename) super(elename) end # Should return a Hash, String or nil. def on_simple_outbound nil end # Given header is a Hash, String or nil. def on_simple_inbound(header, mustunderstand) end def on_outbound h = on_simple_outbound h ? SOAPElement.from_obj(h, elename.namespace) : nil end def on_inbound(header, mustunderstand) h = header.respond_to?(:to_obj) ? header.to_obj : header.data on_simple_inbound(h, mustunderstand) 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/header/handler.rb
tools/jruby-1.5.1/lib/ruby/1.8/soap/header/handler.rb
# SOAP4R - SOAP Header handler item # Copyright (C) 2003, 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/element' module SOAP module Header class Handler attr_reader :elename attr_reader :mustunderstand attr_reader :encodingstyle def initialize(elename) @elename = elename @mustunderstand = false @encodingstyle = nil end # Should return a SOAP/OM, a SOAPHeaderItem or nil. def on_outbound nil end # Given header is a SOAPHeaderItem or nil. def on_inbound(header, mustunderstand = false) # do something. end def on_outbound_headeritem item = on_outbound if item.nil? nil elsif item.is_a?(::SOAP::SOAPHeaderItem) item.elename = @elename item else item.elename = @elename ::SOAP::SOAPHeaderItem.new(item, @mustunderstand, @encodingstyle) end end def on_inbound_headeritem(header) on_inbound(header.element, header.mustunderstand) 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/irb/version.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/version.rb
# # irb/version.rb - irb version definition file # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ishitsuka.com) # # -- # # # module IRB @RELEASE_VERSION = "0.9.5" @LAST_UPDATE_DATE = "05/04/13" 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/irb/ws-for-case-2.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ws-for-case-2.rb
# # irb/ws-for-case-2.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # while true IRB::BINDING_QUEUE.push b = binding 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/irb/completion.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/completion.rb
# # irb/completor.rb - # $Release Version: 0.9$ # $Revision$ # $Date$ # by Keiju ISHITSUKA(keiju@ishitsuka.com) # From Original Idea of shugo@ruby-lang.org # require "readline" module IRB module InputCompletor @RCS_ID='-$Id$-' ReservedWords = [ "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", ] CompletionProc = proc { |input| bind = IRB.conf[:MAIN_CONTEXT].workspace.binding # puts "input: #{input}" case input when /^(\/[^\/]*\/)\.([^.]*)$/ # Regexp receiver = $1 message = Regexp.quote($2) candidates = Regexp.instance_methods(true) select_message(receiver, message, candidates) when /^([^\]]*\])\.([^.]*)$/ # Array receiver = $1 message = Regexp.quote($2) candidates = Array.instance_methods(true) select_message(receiver, message, candidates) when /^([^\}]*\})\.([^.]*)$/ # Proc or Hash receiver = $1 message = Regexp.quote($2) candidates = Proc.instance_methods(true) | Hash.instance_methods(true) select_message(receiver, message, candidates) when /^(:[^:.]*)$/ # Symbol if Symbol.respond_to?(:all_symbols) sym = $1 candidates = Symbol.all_symbols.collect{|s| ":" + s.id2name} candidates.grep(/^#{sym}/) else [] end when /^::([A-Z][^:\.\(]*)$/ # Absolute Constant or class methods receiver = $1 candidates = Object.constants candidates.grep(/^#{receiver}/).collect{|e| "::" + e} when /^(((::)?[A-Z][^:.\(]*)+)::?([^:.]*)$/ # Constant or class methods receiver = $1 message = Regexp.quote($4) begin candidates = eval("#{receiver}.constants | #{receiver}.methods", bind) rescue Exception candidates = [] end candidates.grep(/^#{message}/).collect{|e| receiver + "::" + e} when /^(:[^:.]+)\.([^.]*)$/ # Symbol receiver = $1 message = Regexp.quote($2) candidates = Symbol.instance_methods(true) select_message(receiver, message, candidates) when /^(-?(0[dbo])?[0-9_]+(\.[0-9_]+)?([eE]-?[0-9]+)?)\.([^.]*)$/ # Numeric receiver = $1 message = Regexp.quote($5) begin candidates = eval(receiver, bind).methods rescue Exception candidates = [] end select_message(receiver, message, candidates) when /^(-?0x[0-9a-fA-F_]+)\.([^.]*)$/ # Numeric(0xFFFF) receiver = $1 message = Regexp.quote($2) begin candidates = eval(receiver, bind).methods rescue Exception candidates = [] end select_message(receiver, message, candidates) when /^(\$[^.]*)$/ candidates = global_variables.grep(Regexp.new(Regexp.quote($1))) # when /^(\$?(\.?[^.]+)+)\.([^.]*)$/ when /^((\.?[^.]+)+)\.([^.]*)$/ # variable receiver = $1 message = Regexp.quote($3) gv = eval("global_variables", bind) lv = eval("local_variables", bind) cv = eval("self.class.constants", bind) if (gv | lv | cv).include?(receiver) # foo.func and foo is local var. candidates = eval("#{receiver}.methods", bind) # JRuby specific (JRUBY-2186) candidates = [] unless candidates.is_a?(Array) elsif /^[A-Z]/ =~ receiver and /\./ !~ receiver # Foo::Bar.func begin candidates = eval("#{receiver}.methods", bind) # JRuby specific (JRUBY-2186) candidates = [] unless candidates.is_a?(Array) rescue Exception candidates = [] end else # func1.func2 candidates = [] ObjectSpace.each_object(Module){|m| # JRuby specific (JRUBY-2186) next unless m.respond_to?(:instance_methods) begin name = m.name rescue Exception name = "" end next if name != "IRB::Context" and /^(IRB|SLex|RubyLex|RubyToken)/ =~ name candidates.concat m.instance_methods(false) } candidates.sort! candidates.uniq! end select_message(receiver, message, candidates) when /^\.([^.]*)$/ # unknown(maybe String) receiver = "" message = Regexp.quote($1) candidates = String.instance_methods(true) select_message(receiver, message, candidates) else candidates = eval("methods | private_methods | local_variables | self.class.constants", bind) (candidates|ReservedWords).grep(/^#{Regexp.quote(input)}/) end } Operators = ["%", "&", "*", "**", "+", "-", "/", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", ">>", "[]", "[]=", "^",] def self.select_message(receiver, message, candidates) candidates.grep(/^#{message}/).collect do |e| case e when /^[a-zA-Z_]/ receiver + "." + e when /^[0-9]/ when *Operators #receiver + " " + e end end end end end if Readline.respond_to?("basic_word_break_characters=") Readline.basic_word_break_characters= " \t\n\"\\'`><=;|&{(" end Readline.completion_append_character = nil Readline.completion_proc = IRB::InputCompletor::CompletionProc
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/irb/xmp.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/xmp.rb
# # xmp.rb - irb version of gotoken xmp # $Release Version: 0.9$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(Nippon Rational Inc.) # # -- # # # require "irb" require "irb/frame" class XMP @RCS_ID='-$Id: xmp.rb 11708 2007-02-12 23:01:19Z shyouhei $-' def initialize(bind = nil) IRB.init_config(nil) #IRB.parse_opts #IRB.load_modules IRB.conf[:PROMPT_MODE] = :XMP bind = IRB::Frame.top(1) unless bind ws = IRB::WorkSpace.new(bind) @io = StringInputMethod.new @irb = IRB::Irb.new(ws, @io) @irb.context.ignore_sigint = false # IRB.conf[:IRB_RC].call(@irb.context) if IRB.conf[:IRB_RC] IRB.conf[:MAIN_CONTEXT] = @irb.context end def puts(exps) @io.puts exps if @irb.context.ignore_sigint begin trap_proc_b = trap("SIGINT"){@irb.signal_handle} catch(:IRB_EXIT) do @irb.eval_input end ensure trap("SIGINT", trap_proc_b) end else catch(:IRB_EXIT) do @irb.eval_input end end end class StringInputMethod < IRB::InputMethod def initialize super @exps = [] end def eof? @exps.empty? end def gets while l = @exps.shift next if /^\s+$/ =~ l l.concat "\n" print @prompt, l break end l end def puts(exps) @exps.concat exps.split(/\n/) end end end def xmp(exps, bind = nil) bind = IRB::Frame.top(1) unless bind xmp = XMP.new(bind) xmp.puts exps xmp 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/irb/ruby-token.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ruby-token.rb
# # irb/ruby-token.rb - ruby tokens # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module RubyToken EXPR_BEG = :EXPR_BEG EXPR_MID = :EXPR_MID EXPR_END = :EXPR_END EXPR_ARG = :EXPR_ARG EXPR_FNAME = :EXPR_FNAME EXPR_DOT = :EXPR_DOT EXPR_CLASS = :EXPR_CLASS # for ruby 1.4X if !defined?(Symbol) Symbol = Integer end class Token def initialize(seek, line_no, char_no) @seek = seek @line_no = line_no @char_no = char_no end attr :seek attr :line_no attr :char_no end class TkNode < Token def initialize(seek, line_no, char_no) super end attr :node end class TkId < Token def initialize(seek, line_no, char_no, name) super(seek, line_no, char_no) @name = name end attr :name end class TkVal < Token def initialize(seek, line_no, char_no, value = nil) super(seek, line_no, char_no) @value = value end attr :value end class TkOp < Token attr :name, true end class TkOPASGN < TkOp def initialize(seek, line_no, char_no, op) super(seek, line_no, char_no) op = TkReading2Token[op][0] unless op.kind_of?(Symbol) @op = op end attr :op end class TkUnknownChar < Token def initialize(seek, line_no, char_no, id) super(seek, line_no, char_no) @name = name end attr :name end class TkError < Token end def Token(token, value = nil) case token when String if (tk = TkReading2Token[token]).nil? IRB.fail TkReading2TokenNoKey, token end tk = Token(tk[0], value) if tk.kind_of?(TkOp) tk.name = token end return tk when Symbol if (tk = TkSymbol2Token[token]).nil? IRB.fail TkSymbol2TokenNoKey, token end return Token(tk[0], value) else if (token.ancestors & [TkId, TkVal, TkOPASGN, TkUnknownChar]).empty? token.new(@prev_seek, @prev_line_no, @prev_char_no) else token.new(@prev_seek, @prev_line_no, @prev_char_no, value) end end end TokenDefinitions = [ [:TkCLASS, TkId, "class", EXPR_CLASS], [:TkMODULE, TkId, "module", EXPR_BEG], [:TkDEF, TkId, "def", EXPR_FNAME], [:TkUNDEF, TkId, "undef", EXPR_FNAME], [:TkBEGIN, TkId, "begin", EXPR_BEG], [:TkRESCUE, TkId, "rescue", EXPR_MID], [:TkENSURE, TkId, "ensure", EXPR_BEG], [:TkEND, TkId, "end", EXPR_END], [:TkIF, TkId, "if", EXPR_BEG, :TkIF_MOD], [:TkUNLESS, TkId, "unless", EXPR_BEG, :TkUNLESS_MOD], [:TkTHEN, TkId, "then", EXPR_BEG], [:TkELSIF, TkId, "elsif", EXPR_BEG], [:TkELSE, TkId, "else", EXPR_BEG], [:TkCASE, TkId, "case", EXPR_BEG], [:TkWHEN, TkId, "when", EXPR_BEG], [:TkWHILE, TkId, "while", EXPR_BEG, :TkWHILE_MOD], [:TkUNTIL, TkId, "until", EXPR_BEG, :TkUNTIL_MOD], [:TkFOR, TkId, "for", EXPR_BEG], [:TkBREAK, TkId, "break", EXPR_END], [:TkNEXT, TkId, "next", EXPR_END], [:TkREDO, TkId, "redo", EXPR_END], [:TkRETRY, TkId, "retry", EXPR_END], [:TkIN, TkId, "in", EXPR_BEG], [:TkDO, TkId, "do", EXPR_BEG], [:TkRETURN, TkId, "return", EXPR_MID], [:TkYIELD, TkId, "yield", EXPR_END], [:TkSUPER, TkId, "super", EXPR_END], [:TkSELF, TkId, "self", EXPR_END], [:TkNIL, TkId, "nil", EXPR_END], [:TkTRUE, TkId, "true", EXPR_END], [:TkFALSE, TkId, "false", EXPR_END], [:TkAND, TkId, "and", EXPR_BEG], [:TkOR, TkId, "or", EXPR_BEG], [:TkNOT, TkId, "not", EXPR_BEG], [:TkIF_MOD, TkId], [:TkUNLESS_MOD, TkId], [:TkWHILE_MOD, TkId], [:TkUNTIL_MOD, TkId], [:TkALIAS, TkId, "alias", EXPR_FNAME], [:TkDEFINED, TkId, "defined?", EXPR_END], [:TklBEGIN, TkId, "BEGIN", EXPR_END], [:TklEND, TkId, "END", EXPR_END], [:Tk__LINE__, TkId, "__LINE__", EXPR_END], [:Tk__FILE__, TkId, "__FILE__", EXPR_END], [:TkIDENTIFIER, TkId], [:TkFID, TkId], [:TkGVAR, TkId], [:TkCVAR, TkId], [:TkIVAR, TkId], [:TkCONSTANT, TkId], [:TkINTEGER, TkVal], [:TkFLOAT, TkVal], [:TkSTRING, TkVal], [:TkXSTRING, TkVal], [:TkREGEXP, TkVal], [:TkSYMBOL, TkVal], [:TkDSTRING, TkNode], [:TkDXSTRING, TkNode], [:TkDREGEXP, TkNode], [:TkNTH_REF, TkNode], [:TkBACK_REF, TkNode], [:TkUPLUS, TkOp, "+@"], [:TkUMINUS, TkOp, "-@"], [:TkPOW, TkOp, "**"], [:TkCMP, TkOp, "<=>"], [:TkEQ, TkOp, "=="], [:TkEQQ, TkOp, "==="], [:TkNEQ, TkOp, "!="], [:TkGEQ, TkOp, ">="], [:TkLEQ, TkOp, "<="], [:TkANDOP, TkOp, "&&"], [:TkOROP, TkOp, "||"], [:TkMATCH, TkOp, "=~"], [:TkNMATCH, TkOp, "!~"], [:TkDOT2, TkOp, ".."], [:TkDOT3, TkOp, "..."], [:TkAREF, TkOp, "[]"], [:TkASET, TkOp, "[]="], [:TkLSHFT, TkOp, "<<"], [:TkRSHFT, TkOp, ">>"], [:TkCOLON2, TkOp], [:TkCOLON3, TkOp], # [:OPASGN, TkOp], # +=, -= etc. # [:TkASSOC, TkOp, "=>"], [:TkQUESTION, TkOp, "?"], #? [:TkCOLON, TkOp, ":"], #: [:TkfLPAREN], # func( # [:TkfLBRACK], # func[ # [:TkfLBRACE], # func{ # [:TkSTAR], # *arg [:TkAMPER], # &arg # [:TkSYMBEG], # :SYMBOL [:TkGT, TkOp, ">"], [:TkLT, TkOp, "<"], [:TkPLUS, TkOp, "+"], [:TkMINUS, TkOp, "-"], [:TkMULT, TkOp, "*"], [:TkDIV, TkOp, "/"], [:TkMOD, TkOp, "%"], [:TkBITOR, TkOp, "|"], [:TkBITXOR, TkOp, "^"], [:TkBITAND, TkOp, "&"], [:TkBITNOT, TkOp, "~"], [:TkNOTOP, TkOp, "!"], [:TkBACKQUOTE, TkOp, "`"], [:TkASSIGN, Token, "="], [:TkDOT, Token, "."], [:TkLPAREN, Token, "("], #(exp) [:TkLBRACK, Token, "["], #[arry] [:TkLBRACE, Token, "{"], #{hash} [:TkRPAREN, Token, ")"], [:TkRBRACK, Token, "]"], [:TkRBRACE, Token, "}"], [:TkCOMMA, Token, ","], [:TkSEMICOLON, Token, ";"], [:TkCOMMENT], [:TkRD_COMMENT], [:TkSPACE], [:TkNL], [:TkEND_OF_SCRIPT], [:TkBACKSLASH, TkUnknownChar, "\\"], [:TkAT, TkUnknownChar, "@"], [:TkDOLLAR, TkUnknownChar, "$"], ] # {reading => token_class} # {reading => [token_class, *opt]} TkReading2Token = {} TkSymbol2Token = {} def RubyToken.def_token(token_n, super_token = Token, reading = nil, *opts) token_n = token_n.id2name if token_n.kind_of?(Symbol) if RubyToken.const_defined?(token_n) IRB.fail AlreadyDefinedToken, token_n end token_c = eval("class #{token_n} < #{super_token}; end; #{token_n}") if reading if TkReading2Token[reading] IRB.fail TkReading2TokenDuplicateError, token_n, reading end if opts.empty? TkReading2Token[reading] = [token_c] else TkReading2Token[reading] = [token_c].concat(opts) end end TkSymbol2Token[token_n.intern] = token_c end for defs in TokenDefinitions def_token(*defs) 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/irb/frame.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/frame.rb
# # frame.rb - # $Release Version: 0.9$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(Nihon Rational Software Co.,Ltd) # # -- # # # require "e2mmap" module IRB class Frame extend Exception2MessageMapper def_exception :FrameOverflow, "frame overflow" def_exception :FrameUnderflow, "frame underflow" INIT_STACK_TIMES = 3 CALL_STACK_OFFSET = 3 def initialize @frames = [TOPLEVEL_BINDING] * INIT_STACK_TIMES end def trace_func(event, file, line, id, binding) case event when 'call', 'class' @frames.push binding when 'return', 'end' @frames.pop end end def top(n = 0) bind = @frames[-(n + CALL_STACK_OFFSET)] Fail FrameUnderflow unless bind bind end def bottom(n = 0) bind = @frames[n] Fail FrameOverflow unless bind bind end # singleton functions def Frame.bottom(n = 0) @backtrace.bottom(n) end def Frame.top(n = 0) @backtrace.top(n) end def Frame.sender eval "self", @backtrace.top end @backtrace = Frame.new set_trace_func proc{|event, file, line, id, binding, klass| @backtrace.trace_func(event, file, line, id, binding) } 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/irb/input-method.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/input-method.rb
# # irb/input-method.rb - input methods used irb # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB # # InputMethod # StdioInputMethod # FileInputMethod # (ReadlineInputMethod) # STDIN_FILE_NAME = "(line)" class InputMethod @RCS_ID='-$Id: input-method.rb 11708 2007-02-12 23:01:19Z shyouhei $-' def initialize(file = STDIN_FILE_NAME) @file_name = file end attr_reader :file_name attr_accessor :prompt def gets IRB.fail NotImplementedError, "gets" end public :gets def readable_atfer_eof? false end end class StdioInputMethod < InputMethod def initialize super @line_no = 0 @line = [] end def gets print @prompt @line[@line_no += 1] = $stdin.gets end def eof? $stdin.eof? end def readable_atfer_eof? true end def line(line_no) @line[line_no] end end class FileInputMethod < InputMethod def initialize(file) super @io = open(file) end attr_reader :file_name def eof? @io.eof? end def gets print @prompt l = @io.gets # print @prompt, l l end end begin require "readline" class ReadlineInputMethod < InputMethod include Readline def initialize super @line_no = 0 @line = [] @eof = false end def gets if l = readline(@prompt, false) HISTORY.push(l) if !l.empty? @line[@line_no += 1] = l + "\n" else @eof = true l end end def eof? @eof end def readable_atfer_eof? true end def line(line_no) @line[line_no] end end rescue LoadError 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/irb/help.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/help.rb
# # irb/help.rb - print usage module # $Release Version: 0.9.5$ # $Revision: 16857 $ # $Date: 2008-06-06 17:05:24 +0900 (Fri, 06 Jun 2008) $ # by Keiju ISHITSUKA(keiju@ishitsuka.com) # # -- # # # module IRB def IRB.print_usage lc = IRB.conf[:LC_MESSAGES] path = lc.find("irb/help-message") space_line = false File.foreach(path) do |l| if /^\s*$/ =~ l lc.puts l unless space_line space_line = true next end space_line = false l.sub!(/#.*$/, "") next if /^\s*$/ =~ l lc.puts l 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/irb/locale.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/locale.rb
# # irb/locale.rb - internationalization module # $Release Version: 0.9.5$ # $Revision$ # $Date$ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # autoload :Kconv, "kconv" module IRB class Locale @RCS_ID='-$Id$-' JPDefaultLocale = "ja" LOCALE_DIR = "/lc/" def initialize(locale = nil) @lang = locale || ENV["IRB_LANG"] || ENV["LC_MESSAGES"] || ENV["LC_ALL"] || ENV["LANG"] || "C" end attr_reader :lang def lc2kconv(lang) case lang when "ja_JP.ujis", "ja_JP.euc", "ja_JP.eucJP" Kconv::EUC when "ja_JP.sjis", "ja_JP.SJIS" Kconv::SJIS when /ja_JP.utf-?8/i Kconv::UTF8 end end private :lc2kconv def String(mes) mes = super(mes) case @lang when /^ja/ mes = Kconv::kconv(mes, lc2kconv(@lang)) else mes end mes end def format(*opts) String(super(*opts)) end def gets(*rs) String(super(*rs)) end def readline(*rs) String(super(*rs)) end def print(*opts) ary = opts.collect{|opt| String(opt)} super(*ary) end def printf(*opts) s = format(*opts) print s end def puts(*opts) ary = opts.collect{|opt| String(opt)} super(*ary) end def require(file, priv = nil) rex = Regexp.new("lc/#{Regexp.quote(file)}\.(so|o|sl|rb)?") return false if $".find{|f| f =~ rex} case file when /\.rb$/ begin load(file, priv) $".push file return true rescue LoadError end when /\.(so|o|sl)$/ return super end begin load(f = file + ".rb") $".push f #" return true rescue LoadError return ruby_require(file) end end alias toplevel_load load def load(file, priv=nil) dir = File.dirname(file) dir = "" if dir == "." base = File.basename(file) if /^ja(_JP)?$/ =~ @lang back, @lang = @lang, "C" end begin if dir[0] == ?/ #/ lc_path = search_file(dir, base) return real_load(lc_path, priv) if lc_path end for path in $: lc_path = search_file(path + "/" + dir, base) return real_load(lc_path, priv) if lc_path end ensure @lang = back if back end raise LoadError, "No such file to load -- #{file}" end def real_load(path, priv) src = self.String(File.read(path)) if priv eval("self", TOPLEVEL_BINDING).extend(Module.new {eval(src, nil, path)}) else eval(src, TOPLEVEL_BINDING, path) end end private :real_load def find(file , paths = $:) dir = File.dirname(file) dir = "" if dir == "." base = File.basename(file) if dir[0] == ?/ #/ return lc_path = search_file(dir, base) else for path in $: if lc_path = search_file(path + "/" + dir, base) return lc_path end end end nil end def search_file(path, file) if File.exist?(p1 = path + lc_path(file, "C")) if File.exist?(p2 = path + lc_path(file)) return p2 else end return p1 else end nil end private :search_file def lc_path(file = "", lc = @lang) case lc when "C" LOCALE_DIR + file when /^ja/ LOCALE_DIR + "ja/" + file else LOCALE_DIR + @lang + "/" + file end end private :lc_path 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/irb/extend-command.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/extend-command.rb
# # irb/extend-command.rb - irb extend command # $Release Version: 0.9.5$ # $Revision$ # $Date$ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB # # IRB extended command # module ExtendCommandBundle EXCB = ExtendCommandBundle NO_OVERRIDE = 0 OVERRIDE_PRIVATE_ONLY = 0x01 OVERRIDE_ALL = 0x02 def irb_exit(ret = 0) irb_context.exit(ret) end def irb_context IRB.CurrentContext end @ALIASES = [ [:context, :irb_context, NO_OVERRIDE], [:conf, :irb_context, NO_OVERRIDE], [:irb_quit, :irb_exit, OVERRIDE_PRIVATE_ONLY], [:exit, :irb_exit, OVERRIDE_PRIVATE_ONLY], [:quit, :irb_exit, OVERRIDE_PRIVATE_ONLY], ] @EXTEND_COMMANDS = [ [:irb_current_working_workspace, :CurrentWorkingWorkspace, "irb/cmd/chws", [:irb_print_working_workspace, OVERRIDE_ALL], [:irb_cwws, OVERRIDE_ALL], [:irb_pwws, OVERRIDE_ALL], # [:irb_cww, OVERRIDE_ALL], # [:irb_pww, OVERRIDE_ALL], [:cwws, NO_OVERRIDE], [:pwws, NO_OVERRIDE], # [:cww, NO_OVERRIDE], # [:pww, NO_OVERRIDE], [:irb_current_working_binding, OVERRIDE_ALL], [:irb_print_working_binding, OVERRIDE_ALL], [:irb_cwb, OVERRIDE_ALL], [:irb_pwb, OVERRIDE_ALL], # [:cwb, NO_OVERRIDE], # [:pwb, NO_OVERRIDE] ], [:irb_change_workspace, :ChangeWorkspace, "irb/cmd/chws", [:irb_chws, OVERRIDE_ALL], # [:irb_chw, OVERRIDE_ALL], [:irb_cws, OVERRIDE_ALL], # [:irb_cw, OVERRIDE_ALL], [:chws, NO_OVERRIDE], # [:chw, NO_OVERRIDE], [:cws, NO_OVERRIDE], # [:cw, NO_OVERRIDE], [:irb_change_binding, OVERRIDE_ALL], [:irb_cb, OVERRIDE_ALL], [:cb, NO_OVERRIDE]], [:irb_workspaces, :Workspaces, "irb/cmd/pushws", [:workspaces, NO_OVERRIDE], [:irb_bindings, OVERRIDE_ALL], [:bindings, NO_OVERRIDE]], [:irb_push_workspace, :PushWorkspace, "irb/cmd/pushws", [:irb_pushws, OVERRIDE_ALL], # [:irb_pushw, OVERRIDE_ALL], [:pushws, NO_OVERRIDE], # [:pushw, NO_OVERRIDE], [:irb_push_binding, OVERRIDE_ALL], [:irb_pushb, OVERRIDE_ALL], [:pushb, NO_OVERRIDE]], [:irb_pop_workspace, :PopWorkspace, "irb/cmd/pushws", [:irb_popws, OVERRIDE_ALL], # [:irb_popw, OVERRIDE_ALL], [:popws, NO_OVERRIDE], # [:popw, NO_OVERRIDE], [:irb_pop_binding, OVERRIDE_ALL], [:irb_popb, OVERRIDE_ALL], [:popb, NO_OVERRIDE]], [:irb_load, :Load, "irb/cmd/load"], [:irb_require, :Require, "irb/cmd/load"], [:irb_source, :Source, "irb/cmd/load", [:source, NO_OVERRIDE]], [:irb, :IrbCommand, "irb/cmd/subirb"], [:irb_jobs, :Jobs, "irb/cmd/subirb", [:jobs, NO_OVERRIDE]], [:irb_fg, :Foreground, "irb/cmd/subirb", [:fg, NO_OVERRIDE]], [:irb_kill, :Kill, "irb/cmd/subirb", [:kill, OVERRIDE_PRIVATE_ONLY]], [:irb_help, :Help, "irb/cmd/help", [:help, NO_OVERRIDE]], ] def self.install_extend_commands for args in @EXTEND_COMMANDS def_extend_command(*args) end end # aliases = [commans_alias, flag], ... def self.def_extend_command(cmd_name, cmd_class, load_file = nil, *aliases) case cmd_class when Symbol cmd_class = cmd_class.id2name when String when Class cmd_class = cmd_class.name end if load_file eval %[ def #{cmd_name}(*opts, &b) require "#{load_file}" eval %[ def #{cmd_name}(*opts, &b) ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b) end ] send :#{cmd_name}, *opts, &b end ] else eval %[ def #{cmd_name}(*opts, &b) ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b) end ] end for ali, flag in aliases @ALIASES.push [ali, cmd_name, flag] end end # override = {NO_OVERRIDE, OVERRIDE_PRIVATE_ONLY, OVERRIDE_ALL} def install_alias_method(to, from, override = NO_OVERRIDE) to = to.id2name unless to.kind_of?(String) from = from.id2name unless from.kind_of?(String) if override == OVERRIDE_ALL or (override == OVERRIDE_PRIVATE_ONLY) && !respond_to?(to) or (override == NO_OVERRIDE) && !respond_to?(to, true) target = self (class<<self;self;end).instance_eval{ if target.respond_to?(to, true) && !target.respond_to?(EXCB.irb_original_method_name(to), true) alias_method(EXCB.irb_original_method_name(to), to) end alias_method to, from } else print "irb: warn: can't alias #{to} from #{from}.\n" end end def self.irb_original_method_name(method_name) "irb_" + method_name + "_org" end def self.extend_object(obj) unless (class<<obj;ancestors;end).include?(EXCB) super for ali, com, flg in @ALIASES obj.install_alias_method(ali, com, flg) end end end install_extend_commands end # extension support for Context module ContextExtender CE = ContextExtender @EXTEND_COMMANDS = [ [:eval_history=, "irb/ext/history.rb"], [:use_tracer=, "irb/ext/tracer.rb"], [:math_mode=, "irb/ext/math-mode.rb"], [:use_loader=, "irb/ext/use-loader.rb"], [:save_history=, "irb/ext/save-history.rb"], ] def self.install_extend_commands for args in @EXTEND_COMMANDS def_extend_command(*args) end end def self.def_extend_command(cmd_name, load_file, *aliases) Context.module_eval %[ def #{cmd_name}(*opts, &b) Context.module_eval {remove_method(:#{cmd_name})} require "#{load_file}" send :#{cmd_name}, *opts, &b end for ali in aliases alias_method ali, cmd_name end ] end CE.install_extend_commands end module MethodExtender def def_pre_proc(base_method, extend_method) base_method = base_method.to_s extend_method = extend_method.to_s alias_name = new_alias_name(base_method) module_eval %[ alias_method alias_name, base_method def #{base_method}(*opts) send :#{extend_method}, *opts send :#{alias_name}, *opts end ] end def def_post_proc(base_method, extend_method) base_method = base_method.to_s extend_method = extend_method.to_s alias_name = new_alias_name(base_method) module_eval %[ alias_method alias_name, base_method def #{base_method}(*opts) send :#{alias_name}, *opts send :#{extend_method}, *opts end ] end # return #{prefix}#{name}#{postfix}<num> def new_alias_name(name, prefix = "__alias_of__", postfix = "__") base_name = "#{prefix}#{name}#{postfix}" all_methods = instance_methods(true) + private_instance_methods(true) same_methods = all_methods.grep(/^#{Regexp.quote(base_name)}[0-9]*$/) return base_name if same_methods.empty? no = same_methods.size while !same_methods.include?(alias_name = base_name + no) no += 1 end alias_name 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/irb/ruby-lex.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ruby-lex.rb
# # irb/ruby-lex.rb - ruby lexcal analyzer # $Release Version: 0.9.5$ # $Revision: 16857 $ # $Date: 2008-06-06 17:05:24 +0900 (Fri, 06 Jun 2008) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" require "irb/slex" require "irb/ruby-token" class RubyLex @RCS_ID='-$Id: ruby-lex.rb 16857 2008-06-06 08:05:24Z knu $-' extend Exception2MessageMapper def_exception(:AlreadyDefinedToken, "Already defined token(%s)") def_exception(:TkReading2TokenNoKey, "key nothing(key='%s')") def_exception(:TkSymbol2TokenNoKey, "key nothing(key='%s')") def_exception(:TkReading2TokenDuplicateError, "key duplicate(token_n='%s', key='%s')") def_exception(:SyntaxError, "%s") def_exception(:TerminateLineInput, "Terminate Line Input") include RubyToken class << self attr_accessor :debug_level def debug? @debug_level > 0 end end @debug_level = 0 def initialize lex_init set_input(STDIN) @seek = 0 @exp_line_no = @line_no = 1 @base_char_no = 0 @char_no = 0 @rests = [] @readed = [] @here_readed = [] @indent = 0 @indent_stack = [] @lex_state = EXPR_BEG @space_seen = false @here_header = false @continue = false @line = "" @skip_space = false @readed_auto_clean_up = false @exception_on_syntax_error = true @prompt = nil end attr_accessor :skip_space attr_accessor :readed_auto_clean_up attr_accessor :exception_on_syntax_error attr_reader :seek attr_reader :char_no attr_reader :line_no attr_reader :indent # io functions def set_input(io, p = nil, &block) @io = io if p.respond_to?(:call) @input = p elsif block_given? @input = block else @input = Proc.new{@io.gets} end end def get_readed if idx = @readed.reverse.index("\n") @base_char_no = idx else @base_char_no += @readed.size end readed = @readed.join("") @readed = [] readed end def getc while @rests.empty? # return nil unless buf_input @rests.push nil unless buf_input end c = @rests.shift if @here_header @here_readed.push c else @readed.push c end @seek += 1 if c == "\n" @line_no += 1 @char_no = 0 else @char_no += 1 end c end def gets l = "" while c = getc l.concat(c) break if c == "\n" end return nil if l == "" and c.nil? l end def eof? @io.eof? end def getc_of_rests if @rests.empty? nil else getc end end def ungetc(c = nil) if @here_readed.empty? c2 = @readed.pop else c2 = @here_readed.pop end c = c2 unless c @rests.unshift c #c = @seek -= 1 if c == "\n" @line_no -= 1 if idx = @readed.reverse.index("\n") @char_no = @readed.size - idx else @char_no = @base_char_no + @readed.size end else @char_no -= 1 end end def peek_equal?(str) chrs = str.split(//) until @rests.size >= chrs.size return false unless buf_input end @rests[0, chrs.size] == chrs end def peek_match?(regexp) while @rests.empty? return false unless buf_input end regexp =~ @rests.join("") end def peek(i = 0) while @rests.size <= i return nil unless buf_input end @rests[i] end def buf_input prompt line = @input.call return nil unless line @rests.concat line.split(//) true end private :buf_input def set_prompt(p = nil, &block) p = block if block_given? if p.respond_to?(:call) @prompt = p else @prompt = Proc.new{print p} end end def prompt if @prompt @prompt.call(@ltype, @indent, @continue, @line_no) end end def initialize_input @ltype = nil @quoted = nil @indent = 0 @indent_stack = [] @lex_state = EXPR_BEG @space_seen = false @here_header = false @continue = false prompt @line = "" @exp_line_no = @line_no end def each_top_level_statement initialize_input catch(:TERM_INPUT) do loop do begin @continue = false prompt unless l = lex throw :TERM_INPUT if @line == '' else #p l @line.concat l if @ltype or @continue or @indent > 0 next end end if @line != "\n" yield @line, @exp_line_no end break unless l @line = '' @exp_line_no = @line_no @indent = 0 @indent_stack = [] prompt rescue TerminateLineInput initialize_input prompt get_readed end end end end def lex until (((tk = token).kind_of?(TkNL) || tk.kind_of?(TkEND_OF_SCRIPT)) && !@continue or tk.nil?) #p tk #p @lex_state #p self end line = get_readed # print self.inspect if line == "" and tk.kind_of?(TkEND_OF_SCRIPT) || tk.nil? nil else line end end def token # require "tracer" # Tracer.on @prev_seek = @seek @prev_line_no = @line_no @prev_char_no = @char_no begin begin tk = @OP.match(self) @space_seen = tk.kind_of?(TkSPACE) rescue SyntaxError raise if @exception_on_syntax_error tk = TkError.new(@seek, @line_no, @char_no) end end while @skip_space and tk.kind_of?(TkSPACE) if @readed_auto_clean_up get_readed end # Tracer.off tk end ENINDENT_CLAUSE = [ "case", "class", "def", "do", "for", "if", "module", "unless", "until", "while", "begin" #, "when" ] DEINDENT_CLAUSE = ["end" #, "when" ] PERCENT_LTYPE = { "q" => "\'", "Q" => "\"", "x" => "\`", "r" => "/", "w" => "]", "W" => "]", "s" => ":" } PERCENT_PAREN = { "{" => "}", "[" => "]", "<" => ">", "(" => ")" } Ltype2Token = { "\'" => TkSTRING, "\"" => TkSTRING, "\`" => TkXSTRING, "/" => TkREGEXP, "]" => TkDSTRING, ":" => TkSYMBOL } DLtype2Token = { "\"" => TkDSTRING, "\`" => TkDXSTRING, "/" => TkDREGEXP, } def lex_init() @OP = IRB::SLex.new @OP.def_rules("\0", "\004", "\032") do |op, io| Token(TkEND_OF_SCRIPT) end @OP.def_rules(" ", "\t", "\f", "\r", "\13") do |op, io| @space_seen = true while getc =~ /[ \t\f\r\13]/; end ungetc Token(TkSPACE) end @OP.def_rule("#") do |op, io| identify_comment end @OP.def_rule("=begin", proc{|op, io| @prev_char_no == 0 && peek(0) =~ /\s/}) do |op, io| @ltype = "=" until getc == "\n"; end until peek_equal?("=end") && peek(4) =~ /\s/ until getc == "\n"; end end gets @ltype = nil Token(TkRD_COMMENT) end @OP.def_rule("\n") do |op, io| print "\\n\n" if RubyLex.debug? case @lex_state when EXPR_BEG, EXPR_FNAME, EXPR_DOT @continue = true else @continue = false @lex_state = EXPR_BEG until (@indent_stack.empty? || [TkLPAREN, TkLBRACK, TkLBRACE, TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last)) @indent_stack.pop end end @here_header = false @here_readed = [] Token(TkNL) end @OP.def_rules("*", "**", "=", "==", "===", "=~", "<=>", "<", "<=", ">", ">=", ">>") do |op, io| case @lex_state when EXPR_FNAME, EXPR_DOT @lex_state = EXPR_ARG else @lex_state = EXPR_BEG end Token(op) end @OP.def_rules("!", "!=", "!~") do |op, io| @lex_state = EXPR_BEG Token(op) end @OP.def_rules("<<") do |op, io| tk = nil if @lex_state != EXPR_END && @lex_state != EXPR_CLASS && (@lex_state != EXPR_ARG || @space_seen) c = peek(0) if /\S/ =~ c && (/["'`]/ =~ c || /[\w_]/ =~ c || c == "-") tk = identify_here_document end end unless tk tk = Token(op) case @lex_state when EXPR_FNAME, EXPR_DOT @lex_state = EXPR_ARG else @lex_state = EXPR_BEG end end tk end @OP.def_rules("'", '"') do |op, io| identify_string(op) end @OP.def_rules("`") do |op, io| if @lex_state == EXPR_FNAME @lex_state = EXPR_END Token(op) else identify_string(op) end end @OP.def_rules('?') do |op, io| if @lex_state == EXPR_END @lex_state = EXPR_BEG Token(TkQUESTION) else ch = getc if @lex_state == EXPR_ARG && ch =~ /\s/ ungetc @lex_state = EXPR_BEG; Token(TkQUESTION) else if (ch == '\\') read_escape end @lex_state = EXPR_END Token(TkINTEGER) end end end @OP.def_rules("&", "&&", "|", "||") do |op, io| @lex_state = EXPR_BEG Token(op) end @OP.def_rules("+=", "-=", "*=", "**=", "&=", "|=", "^=", "<<=", ">>=", "||=", "&&=") do |op, io| @lex_state = EXPR_BEG op =~ /^(.*)=$/ Token(TkOPASGN, $1) end @OP.def_rule("+@", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_ARG Token(op) end @OP.def_rule("-@", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_ARG Token(op) end @OP.def_rules("+", "-") do |op, io| catch(:RET) do if @lex_state == EXPR_ARG if @space_seen and peek(0) =~ /[0-9]/ throw :RET, identify_number else @lex_state = EXPR_BEG end elsif @lex_state != EXPR_END and peek(0) =~ /[0-9]/ throw :RET, identify_number else @lex_state = EXPR_BEG end Token(op) end end @OP.def_rule(".") do |op, io| @lex_state = EXPR_BEG if peek(0) =~ /[0-9]/ ungetc identify_number else # for "obj.if" etc. @lex_state = EXPR_DOT Token(TkDOT) end end @OP.def_rules("..", "...") do |op, io| @lex_state = EXPR_BEG Token(op) end lex_int2 end def lex_int2 @OP.def_rules("]", "}", ")") do |op, io| @lex_state = EXPR_END @indent -= 1 @indent_stack.pop Token(op) end @OP.def_rule(":") do |op, io| if @lex_state == EXPR_END || peek(0) =~ /\s/ @lex_state = EXPR_BEG Token(TkCOLON) else @lex_state = EXPR_FNAME; Token(TkSYMBEG) end end @OP.def_rule("::") do |op, io| # p @lex_state.id2name, @space_seen if @lex_state == EXPR_BEG or @lex_state == EXPR_ARG && @space_seen @lex_state = EXPR_BEG Token(TkCOLON3) else @lex_state = EXPR_DOT Token(TkCOLON2) end end @OP.def_rule("/") do |op, io| if @lex_state == EXPR_BEG || @lex_state == EXPR_MID identify_string(op) elsif peek(0) == '=' getc @lex_state = EXPR_BEG Token(TkOPASGN, "/") #/) elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/ identify_string(op) else @lex_state = EXPR_BEG Token("/") #/) end end @OP.def_rules("^") do |op, io| @lex_state = EXPR_BEG Token("^") end # @OP.def_rules("^=") do # @lex_state = EXPR_BEG # Token(OP_ASGN, :^) # end @OP.def_rules(",") do |op, io| @lex_state = EXPR_BEG Token(op) end @OP.def_rules(";") do |op, io| @lex_state = EXPR_BEG until (@indent_stack.empty? || [TkLPAREN, TkLBRACK, TkLBRACE, TkfLPAREN, TkfLBRACK, TkfLBRACE].include?(@indent_stack.last)) @indent_stack.pop end Token(op) end @OP.def_rule("~") do |op, io| @lex_state = EXPR_BEG Token("~") end @OP.def_rule("~@", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_BEG Token("~") end @OP.def_rule("(") do |op, io| @indent += 1 if @lex_state == EXPR_BEG || @lex_state == EXPR_MID @lex_state = EXPR_BEG tk_c = TkfLPAREN else @lex_state = EXPR_BEG tk_c = TkLPAREN end @indent_stack.push tk_c tk = Token(tk_c) end @OP.def_rule("[]", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_ARG Token("[]") end @OP.def_rule("[]=", proc{|op, io| @lex_state == EXPR_FNAME}) do |op, io| @lex_state = EXPR_ARG Token("[]=") end @OP.def_rule("[") do |op, io| @indent += 1 if @lex_state == EXPR_FNAME tk_c = TkfLBRACK else if @lex_state == EXPR_BEG || @lex_state == EXPR_MID tk_c = TkLBRACK elsif @lex_state == EXPR_ARG && @space_seen tk_c = TkLBRACK else tk_c = TkfLBRACK end @lex_state = EXPR_BEG end @indent_stack.push tk_c Token(tk_c) end @OP.def_rule("{") do |op, io| @indent += 1 if @lex_state != EXPR_END && @lex_state != EXPR_ARG tk_c = TkLBRACE else tk_c = TkfLBRACE end @lex_state = EXPR_BEG @indent_stack.push tk_c Token(tk_c) end @OP.def_rule('\\') do |op, io| if getc == "\n" @space_seen = true @continue = true Token(TkSPACE) else ungetc Token("\\") end end @OP.def_rule('%') do |op, io| if @lex_state == EXPR_BEG || @lex_state == EXPR_MID identify_quotation elsif peek(0) == '=' getc Token(TkOPASGN, :%) elsif @lex_state == EXPR_ARG and @space_seen and peek(0) !~ /\s/ identify_quotation else @lex_state = EXPR_BEG Token("%") #)) end end @OP.def_rule('$') do |op, io| identify_gvar end @OP.def_rule('@') do |op, io| if peek(0) =~ /[\w_@]/ ungetc identify_identifier else Token("@") end end # @OP.def_rule("def", proc{|op, io| /\s/ =~ io.peek(0)}) do # |op, io| # @indent += 1 # @lex_state = EXPR_FNAME # # @lex_state = EXPR_END # # until @rests[0] == "\n" or @rests[0] == ";" # # rests.shift # # end # end @OP.def_rule("") do |op, io| printf "MATCH: start %s: %s\n", op, io.inspect if RubyLex.debug? if peek(0) =~ /[0-9]/ t = identify_number elsif peek(0) =~ /[\w_]/ t = identify_identifier end printf "MATCH: end %s: %s\n", op, io.inspect if RubyLex.debug? t end p @OP if RubyLex.debug? end def identify_gvar @lex_state = EXPR_END case ch = getc when /[~_*$?!@\/\\;,=:<>".]/ #" Token(TkGVAR, "$" + ch) when "-" Token(TkGVAR, "$-" + getc) when "&", "`", "'", "+" Token(TkBACK_REF, "$"+ch) when /[1-9]/ while getc =~ /[0-9]/; end ungetc Token(TkNTH_REF) when /\w/ ungetc ungetc identify_identifier else ungetc Token("$") end end def identify_identifier token = "" if peek(0) =~ /[$@]/ token.concat(c = getc) if c == "@" and peek(0) == "@" token.concat getc end end while (ch = getc) =~ /\w|_/ print ":", ch, ":" if RubyLex.debug? token.concat ch end ungetc if (ch == "!" || ch == "?") && token[0,1] =~ /\w/ && peek(0) != "=" token.concat getc end # almost fix token case token when /^\$/ return Token(TkGVAR, token) when /^\@\@/ @lex_state = EXPR_END # p Token(TkCVAR, token) return Token(TkCVAR, token) when /^\@/ @lex_state = EXPR_END return Token(TkIVAR, token) end if @lex_state != EXPR_DOT print token, "\n" if RubyLex.debug? token_c, *trans = TkReading2Token[token] if token_c # reserved word? if (@lex_state != EXPR_BEG && @lex_state != EXPR_FNAME && trans[1]) # modifiers token_c = TkSymbol2Token[trans[1]] @lex_state = trans[0] else if @lex_state != EXPR_FNAME if ENINDENT_CLAUSE.include?(token) # check for ``class = val'' etc. valid = true case token when "class" valid = false unless peek_match?(/^\s*(<<|\w|::)/) when "def" valid = false if peek_match?(/^\s*(([+-\/*&\|^]|<<|>>|\|\||\&\&)=|\&\&|\|\|)/) when "do" valid = false if peek_match?(/^\s*([+-\/*]?=|\*|<|>|\&)/) when *ENINDENT_CLAUSE valid = false if peek_match?(/^\s*([+-\/*]?=|\*|<|>|\&|\|)/) else # no nothing end if valid if token == "do" if ![TkFOR, TkWHILE, TkUNTIL].include?(@indent_stack.last) @indent += 1 @indent_stack.push token_c end else @indent += 1 @indent_stack.push token_c end # p @indent_stack end elsif DEINDENT_CLAUSE.include?(token) @indent -= 1 @indent_stack.pop end @lex_state = trans[0] else @lex_state = EXPR_END end end return Token(token_c, token) end end if @lex_state == EXPR_FNAME @lex_state = EXPR_END if peek(0) == '=' token.concat getc end elsif @lex_state == EXPR_BEG || @lex_state == EXPR_DOT @lex_state = EXPR_ARG else @lex_state = EXPR_END end if token[0, 1] =~ /[A-Z]/ return Token(TkCONSTANT, token) elsif token[token.size - 1, 1] =~ /[!?]/ return Token(TkFID, token) else return Token(TkIDENTIFIER, token) end end def identify_here_document ch = getc # if lt = PERCENT_LTYPE[ch] if ch == "-" ch = getc indent = true end if /['"`]/ =~ ch lt = ch quoted = "" while (c = getc) && c != lt quoted.concat c end else lt = '"' quoted = ch.dup while (c = getc) && c =~ /\w/ quoted.concat c end ungetc end ltback, @ltype = @ltype, lt reserve = [] while ch = getc reserve.push ch if ch == "\\" reserve.push ch = getc elsif ch == "\n" break end end @here_header = false while l = gets l = l.sub(/(:?\r)?\n\z/, '') if (indent ? l.strip : l) == quoted break end end @here_header = true @here_readed.concat reserve while ch = reserve.pop ungetc ch end @ltype = ltback @lex_state = EXPR_END Token(Ltype2Token[lt]) end def identify_quotation ch = getc if lt = PERCENT_LTYPE[ch] ch = getc elsif ch =~ /\W/ lt = "\"" else RubyLex.fail SyntaxError, "unknown type of %string" end # if ch !~ /\W/ # ungetc # next # end #@ltype = lt @quoted = ch unless @quoted = PERCENT_PAREN[ch] identify_string(lt, @quoted) end def identify_number @lex_state = EXPR_END if peek(0) == "0" && peek(1) !~ /[.eE]/ getc case peek(0) when /[xX]/ ch = getc match = /[0-9a-fA-F_]/ when /[bB]/ ch = getc match = /[01_]/ when /[oO]/ ch = getc match = /[0-7_]/ when /[dD]/ ch = getc match = /[0-9_]/ when /[0-7]/ match = /[0-7_]/ when /[89]/ RubyLex.fail SyntaxError, "Illegal octal digit" else return Token(TkINTEGER) end len0 = true non_digit = false while ch = getc if match =~ ch if ch == "_" if non_digit RubyLex.fail SyntaxError, "trailing `#{ch}' in number" else non_digit = ch end else non_digit = false len0 = false end else ungetc if len0 RubyLex.fail SyntaxError, "numeric literal without digits" end if non_digit RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number" end break end end return Token(TkINTEGER) end type = TkINTEGER allow_point = true allow_e = true non_digit = false while ch = getc case ch when /[0-9]/ non_digit = false when "_" non_digit = ch when allow_point && "." if non_digit RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number" end type = TkFLOAT if peek(0) !~ /[0-9]/ type = TkINTEGER ungetc break end allow_point = false when allow_e && "e", allow_e && "E" if non_digit RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number" end type = TkFLOAT if peek(0) =~ /[+-]/ getc end allow_e = false allow_point = false non_digit = ch else if non_digit RubyLex.fail SyntaxError, "trailing `#{non_digit}' in number" end ungetc break end end Token(type) end def identify_string(ltype, quoted = ltype) @ltype = ltype @quoted = quoted subtype = nil begin nest = 0 while ch = getc if @quoted == ch and nest == 0 break elsif @ltype != "'" && @ltype != "]" && @ltype != ":" and ch == "#" subtype = true elsif ch == '\\' #' read_escape end if PERCENT_PAREN.values.include?(@quoted) if PERCENT_PAREN[ch] == @quoted nest += 1 elsif ch == @quoted nest -= 1 end end end if @ltype == "/" if peek(0) =~ /i|m|x|o|e|s|u|n/ getc end end if subtype Token(DLtype2Token[ltype]) else Token(Ltype2Token[ltype]) end ensure @ltype = nil @quoted = nil @lex_state = EXPR_END end end def identify_comment @ltype = "#" while ch = getc # if ch == "\\" #" # read_escape # end if ch == "\n" @ltype = nil ungetc break end end return Token(TkCOMMENT) end def read_escape case ch = getc when "\n", "\r", "\f" when "\\", "n", "t", "r", "f", "v", "a", "e", "b", "s" #" when /[0-7]/ ungetc ch 3.times do case ch = getc when /[0-7]/ when nil break else ungetc break end end when "x" 2.times do case ch = getc when /[0-9a-fA-F]/ when nil break else ungetc break end end when "M" if (ch = getc) != '-' ungetc else if (ch = getc) == "\\" #" read_escape end end when "C", "c" #, "^" if ch == "C" and (ch = getc) != "-" ungetc elsif (ch = getc) == "\\" #" read_escape end else # other characters 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/irb/notifier.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/notifier.rb
# # notifier.rb - output methods used by irb # $Release Version: 0.9.5$ # $Revision: 16857 $ # $Date: 2008-06-06 17:05:24 +0900 (Fri, 06 Jun 2008) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" require "irb/output-method" module IRB module Notifier extend Exception2MessageMapper def_exception :ErrUndefinedNotifier, "undefined notifier level: %d is specified" def_exception :ErrUnrecognizedLevel, "unrecognized notifier level: %s is specified" def def_notifier(prefix = "", output_method = StdioOutputMethod.new) CompositeNotifier.new(prefix, output_method) end module_function :def_notifier class AbstructNotifier def initialize(prefix, base_notifier) @prefix = prefix @base_notifier = base_notifier end attr_reader :prefix def notify? true end def print(*opts) @base_notifier.print prefix, *opts if notify? end def printn(*opts) @base_notifier.printn prefix, *opts if notify? end def printf(format, *opts) @base_notifier.printf(prefix + format, *opts) if notify? end def puts(*objs) if notify? @base_notifier.puts(*objs.collect{|obj| prefix + obj.to_s}) end end def pp(*objs) if notify? @base_notifier.ppx @prefix, *objs end end def ppx(prefix, *objs) if notify? @base_notifier.ppx @prefix+prefix, *objs end end def exec_if yield(@base_notifier) if notify? end end class CompositeNotifier<AbstructNotifier def initialize(prefix, base_notifier) super @notifiers = [D_NOMSG] @level_notifier = D_NOMSG end attr_reader :notifiers def def_notifier(level, prefix = "") notifier = LeveledNotifier.new(self, level, prefix) @notifiers[level] = notifier notifier end attr_reader :level_notifier alias level level_notifier def level_notifier=(value) case value when AbstructNotifier @level_notifier = value when Integer l = @notifiers[value] Notifier.Raise ErrUndefinedNotifer, value unless l @level_notifier = l else Notifier.Raise ErrUnrecognizedLevel, value unless l end end alias level= level_notifier= end class LeveledNotifier<AbstructNotifier include Comparable def initialize(base, level, prefix) super(prefix, base) @level = level end attr_reader :level def <=>(other) @level <=> other.level end def notify? @base_notifier.level >= self end end class NoMsgNotifier<LeveledNotifier def initialize @base_notifier = nil @level = 0 @prefix = "" end def notify? false end end D_NOMSG = NoMsgNotifier.new 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/irb/slex.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/slex.rb
# # irb/slex.rb - simple lex analyzer # $Release Version: 0.9.5$ # $Revision: 16857 $ # $Date: 2008-06-06 17:05:24 +0900 (Fri, 06 Jun 2008) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" require "irb/notifier" module IRB class SLex @RCS_ID='-$Id: slex.rb 16857 2008-06-06 08:05:24Z knu $-' extend Exception2MessageMapper def_exception :ErrNodeNothing, "node nothing" def_exception :ErrNodeAlreadyExists, "node already exists" DOUT = Notifier::def_notifier("SLex::") D_WARN = DOUT::def_notifier(1, "Warn: ") D_DEBUG = DOUT::def_notifier(2, "Debug: ") D_DETAIL = DOUT::def_notifier(4, "Detail: ") DOUT.level = Notifier::D_NOMSG def initialize @head = Node.new("") end def def_rule(token, preproc = nil, postproc = nil, &block) D_DETAIL.pp token postproc = block if block_given? node = create(token, preproc, postproc) end def def_rules(*tokens, &block) if block_given? p = block end for token in tokens def_rule(token, nil, p) end end def preproc(token, proc) node = search(token) node.preproc=proc end #$BMW%A%'%C%/(B? def postproc(token) node = search(token, proc) node.postproc=proc end def search(token) @head.search(token.split(//)) end def create(token, preproc = nil, postproc = nil) @head.create_subnode(token.split(//), preproc, postproc) end def match(token) case token when Array when String return match(token.split(//)) else return @head.match_io(token) end ret = @head.match(token) D_DETAIL.exec_if{D_DEATIL.printf "match end: %s:%s\n", ret, token.inspect} ret end def inspect format("<SLex: @head = %s>", @head.inspect) end #---------------------------------------------------------------------- # # class Node - # #---------------------------------------------------------------------- class Node # if postproc is nil, this node is an abstract node. # if postproc is non-nil, this node is a real node. def initialize(preproc = nil, postproc = nil) @Tree = {} @preproc = preproc @postproc = postproc end attr_accessor :preproc attr_accessor :postproc def search(chrs, opt = nil) return self if chrs.empty? ch = chrs.shift if node = @Tree[ch] node.search(chrs, opt) else if opt chrs.unshift ch self.create_subnode(chrs) else SLex.fail ErrNodeNothing end end end def create_subnode(chrs, preproc = nil, postproc = nil) if chrs.empty? if @postproc D_DETAIL.pp node SLex.fail ErrNodeAlreadyExists else D_DEBUG.puts "change abstract node to real node." @preproc = preproc @postproc = postproc end return self end ch = chrs.shift if node = @Tree[ch] if chrs.empty? if node.postproc DebugLogger.pp node DebugLogger.pp self DebugLogger.pp ch DebugLogger.pp chrs SLex.fail ErrNodeAlreadyExists else D_WARN.puts "change abstract node to real node" node.preproc = preproc node.postproc = postproc end else node.create_subnode(chrs, preproc, postproc) end else if chrs.empty? node = Node.new(preproc, postproc) else node = Node.new node.create_subnode(chrs, preproc, postproc) end @Tree[ch] = node end node end # # chrs: String # character array # io must have getc()/ungetc(); and ungetc() must be # able to be called arbitrary number of times. # def match(chrs, op = "") D_DETAIL.print "match>: ", chrs, "op:", op, "\n" if chrs.empty? if @preproc.nil? || @preproc.call(op, chrs) DOUT.printf(D_DETAIL, "op1: %s\n", op) @postproc.call(op, chrs) else nil end else ch = chrs.shift if node = @Tree[ch] if ret = node.match(chrs, op+ch) return ret else chrs.unshift ch if @postproc and @preproc.nil? || @preproc.call(op, chrs) DOUT.printf(D_DETAIL, "op2: %s\n", op.inspect) ret = @postproc.call(op, chrs) return ret else return nil end end else chrs.unshift ch if @postproc and @preproc.nil? || @preproc.call(op, chrs) DOUT.printf(D_DETAIL, "op3: %s\n", op) @postproc.call(op, chrs) return "" else return nil end end end end def match_io(io, op = "") if op == "" ch = io.getc if ch == nil return nil end else ch = io.getc_of_rests end if ch.nil? if @preproc.nil? || @preproc.call(op, io) D_DETAIL.printf("op1: %s\n", op) @postproc.call(op, io) else nil end else if node = @Tree[ch] if ret = node.match_io(io, op+ch) ret else io.ungetc ch if @postproc and @preproc.nil? || @preproc.call(op, io) DOUT.exec_if{D_DETAIL.printf "op2: %s\n", op.inspect} @postproc.call(op, io) else nil end end else io.ungetc ch if @postproc and @preproc.nil? || @preproc.call(op, io) D_DETAIL.printf("op3: %s\n", op) @postproc.call(op, io) else nil end end end end end end end SLex=IRB::SLex if $0 == __FILE__ # Tracer.on case $1 when "1" tr = SLex.new print "0: ", tr.inspect, "\n" tr.def_rule("=") {print "=\n"} print "1: ", tr.inspect, "\n" tr.def_rule("==") {print "==\n"} print "2: ", tr.inspect, "\n" print "case 1:\n" print tr.match("="), "\n" print "case 2:\n" print tr.match("=="), "\n" print "case 3:\n" print tr.match("=>"), "\n" when "2" tr = SLex.new print "0: ", tr.inspect, "\n" tr.def_rule("=") {print "=\n"} print "1: ", tr.inspect, "\n" tr.def_rule("==", proc{false}) {print "==\n"} print "2: ", tr.inspect, "\n" print "case 1:\n" print tr.match("="), "\n" print "case 2:\n" print tr.match("=="), "\n" print "case 3:\n" print tr.match("=>"), "\n" end exit 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/irb/context.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/context.rb
# # irb/context.rb - irb context # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/workspace" module IRB class Context # # Arguments: # input_method: nil -- stdin or readline # String -- File # other -- using this as InputMethod # def initialize(irb, workspace = nil, input_method = nil, output_method = nil) @irb = irb if workspace @workspace = workspace else @workspace = WorkSpace.new end @thread = Thread.current if defined? Thread # @irb_level = 0 # copy of default configuration @ap_name = IRB.conf[:AP_NAME] @rc = IRB.conf[:RC] @load_modules = IRB.conf[:LOAD_MODULES] @use_readline = IRB.conf[:USE_READLINE] @inspect_mode = IRB.conf[:INSPECT_MODE] self.math_mode = IRB.conf[:MATH_MODE] if IRB.conf[:MATH_MODE] self.use_tracer = IRB.conf[:USE_TRACER] if IRB.conf[:USE_TRACER] self.use_loader = IRB.conf[:USE_LOADER] if IRB.conf[:USE_LOADER] self.eval_history = IRB.conf[:EVAL_HISTORY] if IRB.conf[:EVAL_HISTORY] @ignore_sigint = IRB.conf[:IGNORE_SIGINT] @ignore_eof = IRB.conf[:IGNORE_EOF] @back_trace_limit = IRB.conf[:BACK_TRACE_LIMIT] self.prompt_mode = IRB.conf[:PROMPT_MODE] if IRB.conf[:SINGLE_IRB] or !defined?(JobManager) @irb_name = IRB.conf[:IRB_NAME] else @irb_name = "irb#"+IRB.JobManager.n_jobs.to_s end @irb_path = "(" + @irb_name + ")" case input_method when nil case use_readline? when nil if (defined?(ReadlineInputMethod) && STDIN.tty? && IRB.conf[:PROMPT_MODE] != :INF_RUBY) @io = ReadlineInputMethod.new else @io = StdioInputMethod.new end when false @io = StdioInputMethod.new when true if defined?(ReadlineInputMethod) @io = ReadlineInputMethod.new else @io = StdioInputMethod.new end end when String @io = FileInputMethod.new(input_method) @irb_name = File.basename(input_method) @irb_path = input_method else @io = input_method end self.save_history = IRB.conf[:SAVE_HISTORY] if IRB.conf[:SAVE_HISTORY] if output_method @output_method = output_method else @output_method = StdioOutputMethod.new end @verbose = IRB.conf[:VERBOSE] @echo = IRB.conf[:ECHO] if @echo.nil? @echo = true end @debug_level = IRB.conf[:DEBUG_LEVEL] end def main @workspace.main end attr_reader :workspace_home attr_accessor :workspace attr_reader :thread attr_accessor :io attr_accessor :irb attr_accessor :ap_name attr_accessor :rc attr_accessor :load_modules attr_accessor :irb_name attr_accessor :irb_path attr_reader :use_readline attr_reader :inspect_mode attr_reader :prompt_mode attr_accessor :prompt_i attr_accessor :prompt_s attr_accessor :prompt_c attr_accessor :prompt_n attr_accessor :auto_indent_mode attr_accessor :return_format attr_accessor :ignore_sigint attr_accessor :ignore_eof attr_accessor :echo attr_accessor :verbose attr_reader :debug_level attr_accessor :back_trace_limit alias use_readline? use_readline alias rc? rc alias ignore_sigint? ignore_sigint alias ignore_eof? ignore_eof alias echo? echo def verbose? if @verbose.nil? if defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod) false elsif !STDIN.tty? or @io.kind_of?(FileInputMethod) true else false end end end def prompting? verbose? || (STDIN.tty? && @io.kind_of?(StdioInputMethod) || (defined?(ReadlineInputMethod) && @io.kind_of?(ReadlineInputMethod))) end attr_reader :last_value def set_last_value(value) @last_value = value @workspace.evaluate self, "_ = IRB.CurrentContext.last_value" end attr_reader :irb_name def prompt_mode=(mode) @prompt_mode = mode pconf = IRB.conf[:PROMPT][mode] @prompt_i = pconf[:PROMPT_I] @prompt_s = pconf[:PROMPT_S] @prompt_c = pconf[:PROMPT_C] @prompt_n = pconf[:PROMPT_N] @return_format = pconf[:RETURN] if ai = pconf.include?(:AUTO_INDENT) @auto_indent_mode = ai else @auto_indent_mode = IRB.conf[:AUTO_INDENT] end end def inspect? @inspect_mode.nil? or @inspect_mode end def file_input? @io.class == FileInputMethod end def inspect_mode=(opt) if opt @inspect_mode = opt else @inspect_mode = !@inspect_mode end print "Switch to#{unless @inspect_mode; ' non';end} inspect mode.\n" if verbose? @inspect_mode end def use_readline=(opt) @use_readline = opt print "use readline module\n" if @use_readline end def debug_level=(value) @debug_level = value RubyLex.debug_level = value SLex.debug_level = value end def debug? @debug_level > 0 end def evaluate(line, line_no) @line_no = line_no set_last_value(@workspace.evaluate(self, line, irb_path, line_no)) # @workspace.evaluate("_ = IRB.conf[:MAIN_CONTEXT]._") # @_ = @workspace.evaluate(line, irb_path, line_no) end alias __exit__ exit def exit(ret = 0) IRB.irb_exit(@irb, ret) end NOPRINTING_IVARS = ["@last_value"] NO_INSPECTING_IVARS = ["@irb", "@io"] IDNAME_IVARS = ["@prompt_mode"] alias __inspect__ inspect def inspect array = [] for ivar in instance_variables.sort{|e1, e2| e1 <=> e2} name = ivar.sub(/^@(.*)$/){$1} val = instance_eval(ivar) case ivar when *NOPRINTING_IVARS array.push format("conf.%s=%s", name, "...") when *NO_INSPECTING_IVARS array.push format("conf.%s=%s", name, val.to_s) when *IDNAME_IVARS array.push format("conf.%s=:%s", name, val.id2name) else array.push format("conf.%s=%s", name, val.inspect) end end array.join("\n") end alias __to_s__ to_s alias to_s inspect 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/irb/workspace.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/workspace.rb
# # irb/workspace-binding.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class WorkSpace # create new workspace. set self to main if specified, otherwise # inherit main from TOPLEVEL_BINDING. def initialize(*main) if main[0].kind_of?(Binding) @binding = main.shift elsif IRB.conf[:SINGLE_IRB] @binding = TOPLEVEL_BINDING else case IRB.conf[:CONTEXT_MODE] when 0 # binding in proc on TOPLEVEL_BINDING @binding = eval("proc{binding}.call", TOPLEVEL_BINDING, __FILE__, __LINE__) when 1 # binding in loaded file require "tempfile" f = Tempfile.open("irb-binding") f.print <<EOF $binding = binding EOF f.close load f.path @binding = $binding when 2 # binding in loaded file(thread use) unless defined? BINDING_QUEUE require "thread" IRB.const_set("BINDING_QUEUE", SizedQueue.new(1)) Thread.abort_on_exception = true Thread.start do eval "require \"irb/ws-for-case-2\"", TOPLEVEL_BINDING, __FILE__, __LINE__ end Thread.pass end @binding = BINDING_QUEUE.pop when 3 # binging in function on TOPLEVEL_BINDING(default) @binding = eval("def irb_binding; binding; end; irb_binding", TOPLEVEL_BINDING, __FILE__, __LINE__ - 3) end end if main.empty? @main = eval("self", @binding) else @main = main[0] IRB.conf[:__MAIN__] = @main case @main when Module @binding = eval("IRB.conf[:__MAIN__].module_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__) else begin @binding = eval("IRB.conf[:__MAIN__].instance_eval('binding', __FILE__, __LINE__)", @binding, __FILE__, __LINE__) rescue TypeError IRB.fail CantChangeBinding, @main.inspect end end end eval("_=nil", @binding) end attr_reader :binding attr_reader :main def evaluate(context, statements, file = __FILE__, line = __LINE__) eval(statements, @binding, file, line) end # error message manipulator def filter_backtrace(bt) case IRB.conf[:CONTEXT_MODE] when 0 return nil if bt =~ /\(irb_local_binding\)/ when 1 if(bt =~ %r!/tmp/irb-binding! or bt =~ %r!irb/.*\.rb! or bt =~ /irb\.rb/) return nil end when 2 return nil if bt =~ /irb\/.*\.rb/ when 3 return nil if bt =~ /irb\/.*\.rb/ bt.sub!(/:\s*in `irb_binding'/){""} end bt end def IRB.delete_caller 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/irb/init.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/init.rb
# # irb/init.rb - irb initialize module # $Release Version: 0.9.5$ # $Revision: 24483 $ # $Date: 2009-08-09 17:44:15 +0900 (Sun, 09 Aug 2009) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB # initialize config def IRB.setup(ap_path) IRB.init_config(ap_path) IRB.init_error IRB.parse_opts IRB.run_config IRB.load_modules unless @CONF[:PROMPT][@CONF[:PROMPT_MODE]] IRB.fail(UndefinedPromptMode, @CONF[:PROMPT_MODE]) end end # @CONF default setting def IRB.init_config(ap_path) # class instance variables @TRACER_INITIALIZED = false # default configurations unless ap_path and @CONF[:AP_NAME] ap_path = File.join(File.dirname(File.dirname(__FILE__)), "irb.rb") end @CONF[:AP_NAME] = File::basename(ap_path, ".rb") @CONF[:IRB_NAME] = "irb" @CONF[:IRB_LIB_PATH] = File.dirname(__FILE__) @CONF[:RC] = true @CONF[:LOAD_MODULES] = [] @CONF[:IRB_RC] = nil @CONF[:MATH_MODE] = false @CONF[:USE_READLINE] = false unless defined?(ReadlineInputMethod) @CONF[:INSPECT_MODE] = nil @CONF[:USE_TRACER] = false @CONF[:USE_LOADER] = false @CONF[:IGNORE_SIGINT] = true @CONF[:IGNORE_EOF] = false @CONF[:ECHO] = nil @CONF[:VERBOSE] = nil @CONF[:EVAL_HISTORY] = nil @CONF[:SAVE_HISTORY] = nil @CONF[:BACK_TRACE_LIMIT] = 16 @CONF[:PROMPT] = { :NULL => { :PROMPT_I => nil, :PROMPT_N => nil, :PROMPT_S => nil, :PROMPT_C => nil, :RETURN => "%s\n" }, :DEFAULT => { :PROMPT_I => "%N(%m):%03n:%i> ", :PROMPT_N => "%N(%m):%03n:%i> ", :PROMPT_S => "%N(%m):%03n:%i%l ", :PROMPT_C => "%N(%m):%03n:%i* ", :RETURN => "=> %s\n" }, :CLASSIC => { :PROMPT_I => "%N(%m):%03n:%i> ", :PROMPT_N => "%N(%m):%03n:%i> ", :PROMPT_S => "%N(%m):%03n:%i%l ", :PROMPT_C => "%N(%m):%03n:%i* ", :RETURN => "%s\n" }, :SIMPLE => { :PROMPT_I => ">> ", :PROMPT_N => ">> ", :PROMPT_S => nil, :PROMPT_C => "?> ", :RETURN => "=> %s\n" }, :INF_RUBY => { :PROMPT_I => "%N(%m):%03n:%i> ", # :PROMPT_N => "%N(%m):%03n:%i> ", :PROMPT_N => nil, :PROMPT_S => nil, :PROMPT_C => nil, :RETURN => "%s\n", :AUTO_INDENT => true }, :XMP => { :PROMPT_I => nil, :PROMPT_N => nil, :PROMPT_S => nil, :PROMPT_C => nil, :RETURN => " ==>%s\n" } } @CONF[:PROMPT_MODE] = (STDIN.tty? ? :DEFAULT : :NULL) @CONF[:AUTO_INDENT] = false @CONF[:CONTEXT_MODE] = 3 # use binding in function on TOPLEVEL_BINDING @CONF[:SINGLE_IRB] = false # @CONF[:LC_MESSAGES] = "en" @CONF[:LC_MESSAGES] = Locale.new @CONF[:AT_EXIT] = [] @CONF[:DEBUG_LEVEL] = 1 end def IRB.init_error @CONF[:LC_MESSAGES].load("irb/error.rb") rescue LoadError # ignore; when running from within an archive (JRuby's "complete" jar) this won't load rescue # happens with applet TODO: probably should make this more robust end FEATURE_IOPT_CHANGE_VERSION = "1.9.0" # option analyzing def IRB.parse_opts load_path = [] while opt = ARGV.shift case opt when "-f" @CONF[:RC] = false when "-m" @CONF[:MATH_MODE] = true when "-d" $DEBUG = true when /^-r(.+)?/ opt = $1 || ARGV.shift @CONF[:LOAD_MODULES].push opt if opt when /^-I(.+)?/ opt = $1 || ARGV.shift load_path.concat(opt.split(File::PATH_SEPARATOR)) if opt when /^-K(.)/ $KCODE = $1 when "--inspect" @CONF[:INSPECT_MODE] = true when "--noinspect" @CONF[:INSPECT_MODE] = false when "--readline" @CONF[:USE_READLINE] = true when "--noreadline" @CONF[:USE_READLINE] = false when "--echo" @CONF[:ECHO] = true when "--noecho" @CONF[:ECHO] = false when "--verbose" @CONF[:VERBOSE] = true when "--noverbose" @CONF[:VERBOSE] = false when "--prompt-mode", "--prompt" prompt_mode = ARGV.shift.upcase.tr("-", "_").intern @CONF[:PROMPT_MODE] = prompt_mode when "--noprompt" @CONF[:PROMPT_MODE] = :NULL when "--inf-ruby-mode" @CONF[:PROMPT_MODE] = :INF_RUBY when "--sample-book-mode", "--simple-prompt" @CONF[:PROMPT_MODE] = :SIMPLE when "--tracer" @CONF[:USE_TRACER] = true when "--back-trace-limit" @CONF[:BACK_TRACE_LIMIT] = ARGV.shift.to_i when "--context-mode" @CONF[:CONTEXT_MODE] = ARGV.shift.to_i when "--single-irb" @CONF[:SINGLE_IRB] = true when "--irb_debug" @CONF[:DEBUG_LEVEL] = ARGV.shift.to_i when "-v", "--version" print IRB.version, "\n" exit 0 when "-h", "--help" require "irb/help" IRB.print_usage exit 0 when /^-/ IRB.fail UnrecognizedSwitch, opt else @CONF[:SCRIPT] = opt $0 = opt break end end if RUBY_VERSION >= FEATURE_IOPT_CHANGE_VERSION load_path.collect! do |path| /\A\.\// =~ path ? path : File.expand_path(path) end end $LOAD_PATH.unshift(*load_path) end # running config def IRB.run_config if @CONF[:RC] begin load rc_file rescue LoadError, Errno::ENOENT rescue print "load error: #{rc_file}\n" print $!.class, ": ", $!, "\n" for err in $@[0, $@.size - 2] print "\t", err, "\n" end end end end IRBRC_EXT = "rc" def IRB.rc_file(ext = IRBRC_EXT) if !@CONF[:RC_NAME_GENERATOR] rc_file_generators do |rcgen| @CONF[:RC_NAME_GENERATOR] ||= rcgen if File.exist?(rcgen.call(IRBRC_EXT)) @CONF[:RC_NAME_GENERATOR] = rcgen break end end end @CONF[:RC_NAME_GENERATOR].call ext end # enumerate possible rc-file base name generators def IRB.rc_file_generators if irbrc = ENV["IRBRC"] yield proc{|rc| rc == "rc" ? irbrc : irbrc+rc} end if home = ENV["HOME"] yield proc{|rc| home+"/.irb#{rc}"} end home = Dir.pwd yield proc{|rc| home+"/.irb#{rc}"} yield proc{|rc| home+"/irb#{rc.sub(/\A_?/, '.')}"} yield proc{|rc| home+"/_irb#{rc}"} yield proc{|rc| home+"/$irb#{rc}"} end # loading modules def IRB.load_modules for m in @CONF[:LOAD_MODULES] begin require m rescue print $@[0], ":", $!.class, ": ", $!, "\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/irb/cmd/nop.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/cmd/nop.rb
# # nop.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB module ExtendCommand class Nop @RCS_ID='-$Id: nop.rb 11708 2007-02-12 23:01:19Z shyouhei $-' def self.execute(conf, *opts) command = new(conf) command.execute(*opts) end def initialize(conf) @irb_context = conf end attr_reader :irb_context def irb @irb_context.irb end def execute(*opts) #nop 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/irb/cmd/load.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/cmd/load.rb
# # load.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/nop.rb" require "irb/ext/loader" module IRB module ExtendCommand class Load<Nop include IrbLoader def execute(file_name, priv = nil) # return ruby_load(file_name) unless IRB.conf[:USE_LOADER] return irb_load(file_name, priv) end end class Require<Nop include IrbLoader def execute(file_name) # return ruby_require(file_name) unless IRB.conf[:USE_LOADER] rex = Regexp.new("#{Regexp.quote(file_name)}(\.o|\.rb)?") return false if $".find{|f| f =~ rex} case file_name when /\.rb$/ begin if irb_load(file_name) $".push file_name return true end rescue LoadError end when /\.(so|o|sl)$/ return ruby_require(file_name) end begin irb_load(f = file_name + ".rb") $".push f return true rescue LoadError return ruby_require(file_name) end end end class Source<Nop include IrbLoader def execute(file_name) source_file(file_name) 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/irb/cmd/chws.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/cmd/chws.rb
# # change-ws.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/nop.rb" require "irb/ext/change-ws.rb" module IRB module ExtendCommand class CurrentWorkingWorkspace<Nop def execute(*obj) irb_context.main end end class ChangeWorkspace<Nop def execute(*obj) irb_context.change_workspace(*obj) irb_context.main 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/irb/cmd/help.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/cmd/help.rb
# # help.rb - helper using ri # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # # -- # # # require 'rdoc/ri/ri_driver' module IRB module ExtendCommand module Help begin @ri = RiDriver.new rescue SystemExit else def self.execute(context, *names) names.each do |name| begin @ri.get_info_for(name.to_s) rescue RiError puts $!.message end end 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/irb/cmd/pushws.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/cmd/pushws.rb
# # change-ws.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/nop.rb" require "irb/ext/workspaces.rb" module IRB module ExtendCommand class Workspaces<Nop def execute(*obj) irb_context.workspaces.collect{|ws| ws.main} end end class PushWorkspace<Workspaces def execute(*obj) irb_context.push_workspace(*obj) super end end class PopWorkspace<Workspaces def execute(*obj) irb_context.pop_workspace(*obj) super 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/irb/cmd/fork.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/cmd/fork.rb
# # fork.rb - # $Release Version: 0.9.5 $ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # @RCS_ID='-$Id: fork.rb 11708 2007-02-12 23:01:19Z shyouhei $-' module IRB module ExtendCommand class Fork<Nop def execute(&block) pid = send ExtendCommand.irb_original_method_name("fork") unless pid class<<self alias_method :exit, ExtendCommand.irb_original_method_name('exit') end if iterator? begin yield ensure exit end end end pid 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/irb/cmd/subirb.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/cmd/subirb.rb
#!/usr/local/bin/ruby # # multi.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/nop.rb" require "irb/ext/multi-irb" module IRB module ExtendCommand class IrbCommand<Nop def execute(*obj) IRB.irb(nil, *obj) end end class Jobs<Nop def execute IRB.JobManager end end class Foreground<Nop def execute(key) IRB.JobManager.switch(key) end end class Kill<Nop def execute(*keys) IRB.JobManager.kill(*keys) 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/irb/ext/math-mode.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ext/math-mode.rb
# # math-mode.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "mathn" module IRB class Context attr_reader :math_mode alias math? math_mode def math_mode=(opt) if @math_mode == true && opt == false IRB.fail CantReturnToNormalMode return end @math_mode = opt if math_mode main.extend Math print "start math mode\n" if verbose? end end def inspect? @inspect_mode.nil? && !@math_mode or @inspect_mode 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/irb/ext/change-ws.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ext/change-ws.rb
# # irb/ext/cb.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class Context def home_workspace if defined? @home_workspace @home_workspace else @home_workspace = @workspace end end def change_workspace(*_main) if _main.empty? @workspace = home_workspace return main end @workspace = WorkSpace.new(_main[0]) if !(class<<main;ancestors;end).include?(ExtendCommandBundle) main.extend ExtendCommandBundle end end # def change_binding(*_main) # back = @workspace # @workspace = WorkSpace.new(*_main) # unless _main.empty? # begin # main.extend ExtendCommandBundle # rescue # print "can't change binding to: ", main.inspect, "\n" # @workspace = back # return nil # end # end # @irb_level += 1 # begin # catch(:SU_EXIT) do # @irb.eval_input # end # ensure # @irb_level -= 1 # @workspace = back # end # end # alias change_workspace change_binding 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/irb/ext/save-history.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ext/save-history.rb
#!/usr/local/bin/ruby # # save-history.rb - # $Release Version: 0.9.5$ # $Revision: 24483 $ # $Date: 2009-08-09 17:44:15 +0900 (Sun, 09 Aug 2009) $ # by Keiju ISHITSUKAkeiju@ruby-lang.org) # # -- # # # require "readline" module IRB module HistorySavingAbility @RCS_ID='-$Id: save-history.rb 24483 2009-08-09 08:44:15Z shyouhei $-' end class Context def init_save_history unless (class<<@io;self;end).include?(HistorySavingAbility) @io.extend(HistorySavingAbility) end end def save_history IRB.conf[:SAVE_HISTORY] end def save_history=(val) IRB.conf[:SAVE_HISTORY] = val if val main_context = IRB.conf[:MAIN_CONTEXT] main_context = self unless main_context main_context.init_save_history end end def history_file IRB.conf[:HISTORY_FILE] end def history_file=(hist) IRB.conf[:HISTORY_FILE] = hist end end module HistorySavingAbility include Readline # def HistorySavingAbility.create_finalizer # proc do # if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0 # if hf = IRB.conf[:HISTORY_FILE] # file = File.expand_path(hf) # end # file = IRB.rc_file("_history") unless file # open(file, 'w' ) do |f| # hist = HISTORY.to_a # f.puts(hist[-num..-1] || hist) # end # end # end # end def HistorySavingAbility.extended(obj) # ObjectSpace.define_finalizer(obj, HistorySavingAbility.create_finalizer) IRB.conf[:AT_EXIT].push proc{obj.save_history} obj.load_history obj end def load_history hist = IRB.conf[:HISTORY_FILE] hist = IRB.rc_file("_history") unless hist if File.exist?(hist) open(hist) do |f| f.each {|l| HISTORY << l.chomp} end end end def save_history if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0 if history_file = IRB.conf[:HISTORY_FILE] history_file = File.expand_path(history_file) end history_file = IRB.rc_file("_history") unless history_file open(history_file, 'w' ) do |f| hist = HISTORY.to_a f.puts(hist[-num..-1] || hist) 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/irb/ext/tracer.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ext/tracer.rb
# # irb/lib/tracer.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "tracer" module IRB # initialize tracing function def IRB.initialize_tracer Tracer.verbose = false Tracer.add_filter { |event, file, line, id, binding, *rests| /^#{Regexp.quote(@CONF[:IRB_LIB_PATH])}/ !~ file and File::basename(file) != "irb.rb" } end class Context attr_reader :use_tracer alias use_tracer? use_tracer def use_tracer=(opt) if opt Tracer.set_get_line_procs(@irb_path) { |line_no, *rests| @io.line(line_no) } elsif !opt && @use_tracer Tracer.off end @use_tracer=opt end end class WorkSpace alias __evaluate__ evaluate def evaluate(context, statements, file = nil, line = nil) if context.use_tracer? && file != nil && line != nil Tracer.on begin __evaluate__(context, statements, file, line) ensure Tracer.off end else __evaluate__(context, statements, file || __FILE__, line || __LINE__) end end end IRB.initialize_tracer 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/irb/ext/loader.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ext/loader.rb
# # loader.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class LoadAbort < Exception;end module IrbLoader @RCS_ID='-$Id: loader.rb 11708 2007-02-12 23:01:19Z shyouhei $-' alias ruby_load load alias ruby_require require def irb_load(fn, priv = nil) path = search_file_from_ruby_path(fn) raise LoadError, "No such file to load -- #{fn}" unless path load_file(path, priv) end def search_file_from_ruby_path(fn) if /^#{Regexp.quote(File::Separator)}/ =~ fn return fn if File.exist?(fn) return nil end for path in $: if File.exist?(f = File.join(path, fn)) return f end end return nil end def source_file(path) irb.suspend_name(path, File.basename(path)) do irb.suspend_input_method(FileInputMethod.new(path)) do |back_io| irb.signal_status(:IN_LOAD) do if back_io.kind_of?(FileInputMethod) irb.eval_input else begin irb.eval_input rescue LoadAbort print "load abort!!\n" end end end end end end def load_file(path, priv = nil) irb.suspend_name(path, File.basename(path)) do if priv ws = WorkSpace.new(Module.new) else ws = WorkSpace.new end irb.suspend_workspace(ws) do irb.suspend_input_method(FileInputMethod.new(path)) do |back_io| irb.signal_status(:IN_LOAD) do # p irb.conf if back_io.kind_of?(FileInputMethod) irb.eval_input else begin irb.eval_input rescue LoadAbort print "load abort!!\n" end end end end end end end def old back_io = @io back_path = @irb_path back_name = @irb_name back_scanner = @irb.scanner begin @io = FileInputMethod.new(path) @irb_name = File.basename(path) @irb_path = path @irb.signal_status(:IN_LOAD) do if back_io.kind_of?(FileInputMethod) @irb.eval_input else begin @irb.eval_input rescue LoadAbort print "load abort!!\n" end end end ensure @io = back_io @irb_name = back_name @irb_path = back_path @irb.scanner = back_scanner 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/irb/ext/use-loader.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ext/use-loader.rb
# # use-loader.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "irb/cmd/load" require "irb/ext/loader" class Object alias __original__load__IRB_use_loader__ load alias __original__require__IRB_use_loader__ require end module IRB module ExtendCommandBundle def irb_load(*opts, &b) ExtendCommand::Load.execute(irb_context, *opts, &b) end def irb_require(*opts, &b) ExtendCommand::Require.execute(irb_context, *opts, &b) end end class Context IRB.conf[:USE_LOADER] = false def use_loader IRB.conf[:USE_LOADER] end alias use_loader? use_loader def use_loader=(opt) if IRB.conf[:USE_LOADER] != opt IRB.conf[:USE_LOADER] = opt if opt if !$".include?("irb/cmd/load") end (class<<@workspace.main;self;end).instance_eval { alias_method :load, :irb_load alias_method :require, :irb_require } else (class<<@workspace.main;self;end).instance_eval { alias_method :load, :__original__load__IRB_use_loader__ alias_method :require, :__original__require__IRB_use_loader__ } end end print "Switch to load/require#{unless use_loader; ' non';end} trace mode.\n" if verbose? opt 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/irb/ext/history.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ext/history.rb
# # history.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class Context NOPRINTING_IVARS.push "@eval_history_values" alias _set_last_value set_last_value def set_last_value(value) _set_last_value(value) # @workspace.evaluate self, "_ = IRB.CurrentContext.last_value" if @eval_history #and !@eval_history_values.equal?(llv) @eval_history_values.push @line_no, @last_value @workspace.evaluate self, "__ = IRB.CurrentContext.instance_eval{@eval_history_values}" end @last_value end attr_reader :eval_history def eval_history=(no) if no if defined?(@eval_history) && @eval_history @eval_history_values.size(no) else @eval_history_values = History.new(no) IRB.conf[:__TMP__EHV__] = @eval_history_values @workspace.evaluate(self, "__ = IRB.conf[:__TMP__EHV__]") IRB.conf.delete(:__TMP_EHV__) end else @eval_history_values = nil end @eval_history = no end end class History @RCS_ID='-$Id: history.rb 11708 2007-02-12 23:01:19Z shyouhei $-' def initialize(size = 16) @size = size @contents = [] end def size(size) if size != 0 && size < @size @contents = @contents[@size - size .. @size] end @size = size end def [](idx) begin if idx >= 0 @contents.find{|no, val| no == idx}[1] else @contents[idx][1] end rescue NameError nil end end def push(no, val) @contents.push [no, val] @contents.shift if @size != 0 && @contents.size > @size end alias real_inspect inspect def inspect if @contents.empty? return real_inspect end unless (last = @contents.pop)[1].equal?(self) @contents.push last last = nil end str = @contents.collect{|no, val| if val.equal?(self) "#{no} ...self-history..." else "#{no} #{val.inspect}" end }.join("\n") if str == "" str = "Empty." end @contents.push last if last str 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/irb/ext/multi-irb.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ext/multi-irb.rb
# # irb/multi-irb.rb - multiple irb module # $Release Version: 0.9.5$ # $Revision: 25814 $ # $Date: 2009-11-17 15:51:29 +0900 (Tue, 17 Nov 2009) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # IRB.fail CantShiftToMultiIrbMode unless defined?(Thread) require "thread" module IRB # job management class class JobManager @RCS_ID='-$Id: multi-irb.rb 25814 2009-11-17 06:51:29Z shyouhei $-' def initialize # @jobs = [[thread, irb],...] @jobs = [] @current_job = nil end attr_accessor :current_job def n_jobs @jobs.size end def thread(key) th, irb = search(key) th end def irb(key) th, irb = search(key) irb end def main_thread @jobs[0][0] end def main_irb @jobs[0][1] end def insert(irb) @jobs.push [Thread.current, irb] end def switch(key) th, irb = search(key) IRB.fail IrbAlreadyDead unless th.alive? IRB.fail IrbSwitchedToCurrentThread if th == Thread.current @current_job = irb th.run Thread.stop @current_job = irb(Thread.current) end def kill(*keys) for key in keys th, irb = search(key) IRB.fail IrbAlreadyDead unless th.alive? th.exit end end def search(key) job = case key when Integer @jobs[key] when Irb @jobs.find{|k, v| v.equal?(key)} when Thread @jobs.assoc(key) else @jobs.find{|k, v| v.context.main.equal?(key)} end IRB.fail NoSuchJob, key if job.nil? job end def delete(key) case key when Integer IRB.fail NoSuchJob, key unless @jobs[key] @jobs[key] = nil else catch(:EXISTS) do @jobs.each_index do |i| if @jobs[i] and (@jobs[i][0] == key || @jobs[i][1] == key || @jobs[i][1].context.main.equal?(key)) @jobs[i] = nil throw :EXISTS end end IRB.fail NoSuchJob, key end end until assoc = @jobs.pop; end unless @jobs.empty? @jobs.push assoc end def inspect ary = [] @jobs.each_index do |i| th, irb = @jobs[i] next if th.nil? if th.alive? if th.stop? t_status = "stop" else t_status = "running" end else t_status = "exited" end ary.push format("#%d->%s on %s (%s: %s)", i, irb.context.irb_name, irb.context.main, th, t_status) end ary.join("\n") end end @JobManager = JobManager.new def IRB.JobManager @JobManager end def IRB.CurrentContext IRB.JobManager.irb(Thread.current).context end # invoke multi-irb def IRB.irb(file = nil, *main) workspace = WorkSpace.new(*main) parent_thread = Thread.current Thread.start do begin irb = Irb.new(workspace, file) rescue print "Subirb can't start with context(self): ", workspace.main.inspect, "\n" print "return to main irb\n" Thread.pass Thread.main.wakeup Thread.exit end @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] @JobManager.insert(irb) @JobManager.current_job = irb begin system_exit = false catch(:IRB_EXIT) do irb.eval_input end rescue SystemExit system_exit = true raise #fail ensure unless system_exit @JobManager.delete(irb) if parent_thread.alive? @JobManager.current_job = @JobManager.irb(parent_thread) parent_thread.run else @JobManager.current_job = @JobManager.main_irb @JobManager.main_thread.run end end end end Thread.stop @JobManager.current_job = @JobManager.irb(Thread.current) end # class Context # def set_last_value(value) # @last_value = value # @workspace.evaluate "_ = IRB.JobManager.irb(Thread.current).context.last_value" # if @eval_history #and !@__.equal?(@last_value) # @eval_history_values.push @line_no, @last_value # @workspace.evaluate "__ = IRB.JobManager.irb(Thread.current).context.instance_eval{@eval_history_values}" # end # @last_value # end # end # module ExtendCommand # def irb_context # IRB.JobManager.irb(Thread.current).context # end # # alias conf irb_context # end @CONF[:SINGLE_IRB_MODE] = false @JobManager.insert(@CONF[:MAIN_CONTEXT].irb) @JobManager.current_job = @CONF[:MAIN_CONTEXT].irb class Irb def signal_handle unless @context.ignore_sigint? print "\nabort!!\n" if @context.verbose? exit end case @signal_status when :IN_INPUT print "^C\n" IRB.JobManager.thread(self).raise RubyLex::TerminateLineInput when :IN_EVAL IRB.irb_abort(self) when :IN_LOAD IRB.irb_abort(self, LoadAbort) when :IN_IRB # ignore else # ignore other cases as well end end end trap("SIGINT") do @JobManager.current_job.signal_handle Thread.stop 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/irb/ext/workspaces.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/ext/workspaces.rb
# # push-ws.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # module IRB class Context def irb_level workspace_stack.size end def workspaces if defined? @workspaces @workspaces else @workspaces = [] end end def push_workspace(*_main) if _main.empty? if workspaces.empty? print "No other workspace\n" return nil end ws = workspaces.pop workspaces.push @workspace @workspace = ws return workspaces end workspaces.push @workspace @workspace = WorkSpace.new(@workspace.binding, _main[0]) if !(class<<main;ancestors;end).include?(ExtendCommandBundle) main.extend ExtendCommandBundle end end def pop_workspace if workspaces.empty? print "workspace stack empty\n" return end @workspace = workspaces.pop 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/irb/lc/error.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/lc/error.rb
# # irb/lc/error.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" module IRB # exceptions extend Exception2MessageMapper def_exception :UnrecognizedSwitch, "Unrecognized switch: %s" def_exception :NotImplementedError, "Need to define `%s'" def_exception :CantReturnToNormalMode, "Can't return to normal mode." def_exception :IllegalParameter, "Illegal parameter(%s)." def_exception :IrbAlreadyDead, "Irb is already dead." def_exception :IrbSwitchedToCurrentThread, "Switched to current thread." def_exception :NoSuchJob, "No such job(%s)." def_exception :CantShiftToMultiIrbMode, "Can't shift to multi irb mode." def_exception :CantChangeBinding, "Can't change binding to (%s)." def_exception :UndefinedPromptMode, "Undefined prompt mode(%s)." 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/irb/lc/ja/error.rb
tools/jruby-1.5.1/lib/ruby/1.8/irb/lc/ja/error.rb
# # irb/lc/ja/error.rb - # $Release Version: 0.9.5$ # $Revision: 11708 $ # $Date: 2007-02-13 08:01:19 +0900 (Tue, 13 Feb 2007) $ # by Keiju ISHITSUKA(keiju@ruby-lang.org) # # -- # # # require "e2mmap" module IRB # exceptions extend Exception2MessageMapper def_exception :UnrecognizedSwitch, '$B%9%$%C%A(B(%s)$B$,J,$j$^$;$s(B' def_exception :NotImplementedError, '`%s\'$B$NDj5A$,I,MW$G$9(B' def_exception :CantReturnToNormalMode, 'Normal$B%b!<%I$KLa$l$^$;$s(B.' def_exception :IllegalParameter, '$B%Q%i%a!<%?(B(%s)$B$,4V0c$C$F$$$^$9(B.' def_exception :IrbAlreadyDead, 'Irb$B$O4{$K;`$s$G$$$^$9(B.' def_exception :IrbSwitchedToCurrentThread, '$B%+%l%s%H%9%l%C%I$K@Z$jBX$o$j$^$7$?(B.' def_exception :NoSuchJob, '$B$=$N$h$&$J%8%g%V(B(%s)$B$O$"$j$^$;$s(B.' def_exception :CantShiftToMultiIrbMode, 'multi-irb mode$B$K0\$l$^$;$s(B.' def_exception :CantChangeBinding, '$B%P%$%s%G%#%s%0(B(%s)$B$KJQ99$G$-$^$;$s(B.' def_exception :UndefinedPromptMode, '$B%W%m%s%W%H%b!<%I(B(%s)$B$ODj5A$5$l$F$$$^$;$s(B.' 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/rss/content.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/content.rb
require "rss/rss" module RSS CONTENT_PREFIX = 'content' CONTENT_URI = "http://purl.org/rss/1.0/modules/content/" module ContentModel extend BaseModel ELEMENTS = ["#{CONTENT_PREFIX}_encoded"] def self.append_features(klass) super klass.install_must_call_validator(CONTENT_PREFIX, CONTENT_URI) ELEMENTS.each do |full_name| name = full_name[(CONTENT_PREFIX.size + 1)..-1] klass.install_text_element(name, CONTENT_URI, "?", full_name) end end end prefix_size = CONTENT_PREFIX.size + 1 ContentModel::ELEMENTS.each do |full_name| name = full_name[prefix_size..-1] BaseListener.install_get_text_element(CONTENT_URI, name, full_name) end end require 'rss/content/1.0' require 'rss/content/2.0'
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/rss/syndication.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/syndication.rb
require "rss/1.0" module RSS SY_PREFIX = 'sy' SY_URI = "http://purl.org/rss/1.0/modules/syndication/" RDF.install_ns(SY_PREFIX, SY_URI) module SyndicationModel extend BaseModel ELEMENTS = [] def self.append_features(klass) super klass.install_must_call_validator(SY_PREFIX, SY_URI) klass.module_eval do [ ["updatePeriod"], ["updateFrequency", :positive_integer] ].each do |name, type| install_text_element(name, SY_URI, "?", "#{SY_PREFIX}_#{name}", type, "#{SY_PREFIX}:#{name}") end %w(updateBase).each do |name| install_date_element(name, SY_URI, "?", "#{SY_PREFIX}_#{name}", 'w3cdtf', "#{SY_PREFIX}:#{name}") end end klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) alias_method(:_sy_updatePeriod=, :sy_updatePeriod=) def sy_updatePeriod=(new_value) new_value = new_value.strip validate_sy_updatePeriod(new_value) if @do_validate self._sy_updatePeriod = new_value end EOC end private SY_UPDATEPERIOD_AVAILABLE_VALUES = %w(hourly daily weekly monthly yearly) def validate_sy_updatePeriod(value) unless SY_UPDATEPERIOD_AVAILABLE_VALUES.include?(value) raise NotAvailableValueError.new("updatePeriod", value) end end end class RDF class Channel; include SyndicationModel; end end prefix_size = SY_PREFIX.size + 1 SyndicationModel::ELEMENTS.uniq! SyndicationModel::ELEMENTS.each do |full_name| name = full_name[prefix_size..-1] BaseListener.install_get_text_element(SY_URI, name, full_name) 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/rss/converter.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/converter.rb
require "rss/utils" module RSS class Converter include Utils def initialize(to_enc, from_enc=nil) normalized_to_enc = to_enc.downcase.gsub(/-/, '_') from_enc ||= 'utf-8' normalized_from_enc = from_enc.downcase.gsub(/-/, '_') if normalized_to_enc == normalized_from_enc def_same_enc() else def_diff_enc = "def_to_#{normalized_to_enc}_from_#{normalized_from_enc}" if respond_to?(def_diff_enc) __send__(def_diff_enc) else def_else_enc(to_enc, from_enc) end end end def convert(value) value end def def_convert(depth=0) instance_eval(<<-EOC, *get_file_and_line_from_caller(depth)) def convert(value) if value.kind_of?(String) #{yield('value')} else value end end EOC end def def_iconv_convert(to_enc, from_enc, depth=0) begin require "iconv" @iconv = Iconv.new(to_enc, from_enc) def_convert(depth+1) do |value| <<-EOC begin @iconv.iconv(#{value}) rescue Iconv::Failure raise ConversionError.new(#{value}, "#{to_enc}", "#{from_enc}") end EOC end rescue LoadError, ArgumentError, SystemCallError raise UnknownConversionMethodError.new(to_enc, from_enc) end end def def_else_enc(to_enc, from_enc) def_iconv_convert(to_enc, from_enc, 0) end def def_same_enc() def_convert do |value| value end end def def_uconv_convert_if_can(meth, to_enc, from_enc, nkf_arg) begin require "uconv" def_convert(1) do |value| <<-EOC begin Uconv.#{meth}(#{value}) rescue Uconv::Error raise ConversionError.new(#{value}, "#{to_enc}", "#{from_enc}") end EOC end rescue LoadError require 'nkf' if NKF.const_defined?(:UTF8) def_convert(1) do |value| "NKF.nkf(#{nkf_arg.dump}, #{value})" end else def_iconv_convert(to_enc, from_enc, 1) end end end def def_to_euc_jp_from_utf_8 def_uconv_convert_if_can('u8toeuc', 'EUC-JP', 'UTF-8', '-We') end def def_to_utf_8_from_euc_jp def_uconv_convert_if_can('euctou8', 'UTF-8', 'EUC-JP', '-Ew') end def def_to_shift_jis_from_utf_8 def_uconv_convert_if_can('u8tosjis', 'Shift_JIS', 'UTF-8', '-Ws') end def def_to_utf_8_from_shift_jis def_uconv_convert_if_can('sjistou8', 'UTF-8', 'Shift_JIS', '-Sw') end def def_to_euc_jp_from_shift_jis require "nkf" def_convert do |value| "NKF.nkf('-Se', #{value})" end end def def_to_shift_jis_from_euc_jp require "nkf" def_convert do |value| "NKF.nkf('-Es', #{value})" end end def def_to_euc_jp_from_iso_2022_jp require "nkf" def_convert do |value| "NKF.nkf('-Je', #{value})" end end def def_to_iso_2022_jp_from_euc_jp require "nkf" def_convert do |value| "NKF.nkf('-Ej', #{value})" end end def def_to_utf_8_from_iso_8859_1 def_convert do |value| "#{value}.unpack('C*').pack('U*')" end end def def_to_iso_8859_1_from_utf_8 def_convert do |value| <<-EOC array_utf8 = #{value}.unpack('U*') array_enc = [] array_utf8.each do |num| if num <= 0xFF array_enc << num else array_enc.concat "&\#\#{num};".unpack('C*') end end array_enc.pack('C*') EOC 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/rss/taxonomy.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/taxonomy.rb
require "rss/1.0" require "rss/dublincore" module RSS TAXO_PREFIX = "taxo" TAXO_URI = "http://purl.org/rss/1.0/modules/taxonomy/" RDF.install_ns(TAXO_PREFIX, TAXO_URI) TAXO_ELEMENTS = [] %w(link).each do |name| full_name = "#{TAXO_PREFIX}_#{name}" BaseListener.install_get_text_element(TAXO_URI, name, full_name) TAXO_ELEMENTS << "#{TAXO_PREFIX}_#{name}" end %w(topic topics).each do |name| class_name = Utils.to_class_name(name) BaseListener.install_class_name(TAXO_URI, name, "Taxonomy#{class_name}") TAXO_ELEMENTS << "#{TAXO_PREFIX}_#{name}" end module TaxonomyTopicsModel extend BaseModel def self.append_features(klass) super klass.install_must_call_validator(TAXO_PREFIX, TAXO_URI) %w(topics).each do |name| klass.install_have_child_element(name, TAXO_URI, "?", "#{TAXO_PREFIX}_#{name}") end end class TaxonomyTopics < Element include RSS10 Bag = ::RSS::RDF::Bag class << self def required_prefix TAXO_PREFIX end def required_uri TAXO_URI end end @tag_name = "topics" install_have_child_element("Bag", RDF::URI, nil) install_must_call_validator('rdf', RDF::URI) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.Bag = args[0] end self.Bag ||= Bag.new end def full_name tag_name_with_prefix(TAXO_PREFIX) end def maker_target(target) target.taxo_topics end def resources if @Bag @Bag.lis.collect do |li| li.resource end else [] end end end end module TaxonomyTopicModel extend BaseModel def self.append_features(klass) super var_name = "#{TAXO_PREFIX}_topic" klass.install_have_children_element("topic", TAXO_URI, "*", var_name) end class TaxonomyTopic < Element include RSS10 include DublinCoreModel include TaxonomyTopicsModel class << self def required_prefix TAXO_PREFIX end def required_uri TAXO_URI end end @tag_name = "topic" install_get_attribute("about", ::RSS::RDF::URI, true, nil, nil, "#{RDF::PREFIX}:about") install_text_element("link", TAXO_URI, "?", "#{TAXO_PREFIX}_link") def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end def full_name tag_name_with_prefix(TAXO_PREFIX) end def maker_target(target) target.new_taxo_topic end end end class RDF include TaxonomyTopicModel class Channel include TaxonomyTopicsModel end class Item; include TaxonomyTopicsModel; 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/rss/maker.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker.rb
require "rss/rss" module RSS module Maker MAKERS = {} class << self def make(version, &block) m = maker(version) raise UnsupportedMakerVersionError.new(version) if m.nil? m[:maker].make(m[:version], &block) end def maker(version) MAKERS[version] end def add_maker(version, normalized_version, maker) MAKERS[version] = {:maker => maker, :version => normalized_version} end def versions MAKERS.keys.uniq.sort end def makers MAKERS.values.collect {|info| info[:maker]}.uniq end end end end require "rss/maker/1.0" require "rss/maker/2.0" require "rss/maker/feed" require "rss/maker/entry" require "rss/maker/content" require "rss/maker/dublincore" require "rss/maker/slash" require "rss/maker/syndication" require "rss/maker/taxonomy" require "rss/maker/trackback" require "rss/maker/image" require "rss/maker/itunes"
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/rss/rexmlparser.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/rexmlparser.rb
require "rexml/document" require "rexml/streamlistener" /\A(\d+)\.(\d+)(?:\.\d+)+\z/ =~ REXML::Version if ([$1.to_i, $2.to_i] <=> [2, 5]) < 0 raise LoadError, "needs REXML 2.5 or later (#{REXML::Version})" end module RSS class REXMLParser < BaseParser class << self def listener REXMLListener end end private def _parse begin REXML::Document.parse_stream(@rss, @listener) rescue RuntimeError => e raise NotWellFormedError.new{e.message} rescue REXML::ParseException => e context = e.context line = context[0] if context raise NotWellFormedError.new(line){e.message} end end end class REXMLListener < BaseListener include REXML::StreamListener include ListenerMixin class << self def raise_for_undefined_entity? false end end def xmldecl(version, encoding, standalone) super(version, encoding, standalone == "yes") # Encoding is converted to UTF-8 when REXML parse XML. @encoding = 'UTF-8' end alias_method(:cdata, :text) 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/rss/utils.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/utils.rb
module RSS module Utils module_function # Convert a name_with_underscores to CamelCase. def to_class_name(name) name.split(/[_\-]/).collect do |part| "#{part[0, 1].upcase}#{part[1..-1]}" end.join("") end def get_file_and_line_from_caller(i=0) file, line, = caller[i].split(':') line = line.to_i line += 1 if i.zero? [file, line] end # escape '&', '"', '<' and '>' for use in HTML. def html_escape(s) s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;") end alias h html_escape # If +value+ is an instance of class +klass+, return it, else # create a new instance of +klass+ with value +value+. def new_with_value_if_need(klass, value) if value.is_a?(klass) value else klass.new(value) end end def element_initialize_arguments?(args) [true, false].include?(args[0]) and args[1].is_a?(Hash) end module YesCleanOther module_function def parse(value) if [true, false, nil].include?(value) value else case value.to_s when /\Ayes\z/i true when /\Aclean\z/i false else nil end end end end module YesOther module_function def parse(value) if [true, false].include?(value) value else /\Ayes\z/i.match(value.to_s) ? true : false end end end module CSV module_function def parse(value, &block) if value.is_a?(String) value = value.strip.split(/\s*,\s*/) value = value.collect(&block) if block_given? value else value end end end module InheritedReader def inherited_reader(constant_name) base_class = inherited_base result = base_class.const_get(constant_name) found_base_class = false ancestors.reverse_each do |klass| if found_base_class if klass.const_defined?(constant_name) result = yield(result, klass.const_get(constant_name)) end else found_base_class = klass == base_class end end result end def inherited_array_reader(constant_name) inherited_reader(constant_name) do |result, current| current + result end end def inherited_hash_reader(constant_name) inherited_reader(constant_name) do |result, current| result.merge(current) 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/rss/xml.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/xml.rb
require "rss/utils" module RSS module XML class Element include Enumerable attr_reader :name, :prefix, :uri, :attributes, :children def initialize(name, prefix=nil, uri=nil, attributes={}, children=[]) @name = name @prefix = prefix @uri = uri @attributes = attributes if children.is_a?(String) or !children.respond_to?(:each) @children = [children] else @children = children end end def [](name) @attributes[name] end def []=(name, value) @attributes[name] = value end def <<(child) @children << child end def each(&block) @children.each(&block) end def ==(other) other.kind_of?(self.class) and @name == other.name and @uri == other.uri and @attributes == other.attributes and @children == other.children end def to_s rv = "<#{full_name}" attributes.each do |key, value| rv << " #{Utils.html_escape(key)}=\"#{Utils.html_escape(value)}\"" end if children.empty? rv << "/>" else rv << ">" children.each do |child| rv << child.to_s end rv << "</#{full_name}>" end rv end def full_name if @prefix "#{@prefix}:#{@name}" else @name 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/rss/parser.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/parser.rb
require "forwardable" require "open-uri" require "rss/rss" require "rss/xml" module RSS class NotWellFormedError < Error attr_reader :line, :element # Create a new NotWellFormedError for an error at +line+ # in +element+. If a block is given the return value of # the block ends up in the error message. def initialize(line=nil, element=nil) message = "This is not well formed XML" if element or line message << "\nerror occurred" message << " in #{element}" if element message << " at about #{line} line" if line end message << "\n#{yield}" if block_given? super(message) end end class XMLParserNotFound < Error def initialize super("available XML parser was not found in " << "#{AVAILABLE_PARSER_LIBRARIES.inspect}.") end end class NotValidXMLParser < Error def initialize(parser) super("#{parser} is not an available XML parser. " << "Available XML parser"<< (AVAILABLE_PARSERS.size > 1 ? "s are ": " is ") << "#{AVAILABLE_PARSERS.inspect}.") end end class NSError < InvalidRSSError attr_reader :tag, :prefix, :uri def initialize(tag, prefix, require_uri) @tag, @prefix, @uri = tag, prefix, require_uri super("prefix <#{prefix}> doesn't associate uri " << "<#{require_uri}> in tag <#{tag}>") end end class Parser extend Forwardable class << self @@default_parser = nil def default_parser @@default_parser || AVAILABLE_PARSERS.first end # Set @@default_parser to new_value if it is one of the # available parsers. Else raise NotValidXMLParser error. def default_parser=(new_value) if AVAILABLE_PARSERS.include?(new_value) @@default_parser = new_value else raise NotValidXMLParser.new(new_value) end end def parse(rss, do_validate=true, ignore_unknown_element=true, parser_class=default_parser) parser = new(rss, parser_class) parser.do_validate = do_validate parser.ignore_unknown_element = ignore_unknown_element parser.parse end end def_delegators(:@parser, :parse, :rss, :ignore_unknown_element, :ignore_unknown_element=, :do_validate, :do_validate=) def initialize(rss, parser_class=self.class.default_parser) @parser = parser_class.new(normalize_rss(rss)) end private # Try to get the XML associated with +rss+. # Return +rss+ if it already looks like XML, or treat it as a URI, # or a file to get the XML, def normalize_rss(rss) return rss if maybe_xml?(rss) uri = to_uri(rss) if uri.respond_to?(:read) uri.read elsif !rss.tainted? and File.readable?(rss) File.open(rss) {|f| f.read} else rss end end # maybe_xml? tests if source is a string that looks like XML. def maybe_xml?(source) source.is_a?(String) and /</ =~ source end # Attempt to convert rss to a URI, but just return it if # there's a ::URI::Error def to_uri(rss) return rss if rss.is_a?(::URI::Generic) begin ::URI.parse(rss) rescue ::URI::Error rss end end end class BaseParser class << self def raise_for_undefined_entity? listener.raise_for_undefined_entity? end end def initialize(rss) @listener = self.class.listener.new @rss = rss end def rss @listener.rss end def ignore_unknown_element @listener.ignore_unknown_element end def ignore_unknown_element=(new_value) @listener.ignore_unknown_element = new_value end def do_validate @listener.do_validate end def do_validate=(new_value) @listener.do_validate = new_value end def parse if @listener.rss.nil? _parse end @listener.rss end end class BaseListener extend Utils class << self @@accessor_bases = {} @@registered_uris = {} @@class_names = {} # return the setter for the uri, tag_name pair, or nil. def setter(uri, tag_name) _getter = getter(uri, tag_name) if _getter "#{_getter}=" else nil end end def getter(uri, tag_name) (@@accessor_bases[uri] || {})[tag_name] end # return the tag_names for setters associated with uri def available_tags(uri) (@@accessor_bases[uri] || {}).keys end # register uri against this name. def register_uri(uri, name) @@registered_uris[name] ||= {} @@registered_uris[name][uri] = nil end # test if this uri is registered against this name def uri_registered?(uri, name) @@registered_uris[name].has_key?(uri) end # record class_name for the supplied uri and tag_name def install_class_name(uri, tag_name, class_name) @@class_names[uri] ||= {} @@class_names[uri][tag_name] = class_name end # retrieve class_name for the supplied uri and tag_name # If it doesn't exist, capitalize the tag_name def class_name(uri, tag_name) name = (@@class_names[uri] || {})[tag_name] return name if name tag_name = tag_name.gsub(/[_\-]([a-z]?)/) do $1.upcase end tag_name[0, 1].upcase + tag_name[1..-1] end def install_get_text_element(uri, name, accessor_base) install_accessor_base(uri, name, accessor_base) def_get_text_element(uri, name, *get_file_and_line_from_caller(1)) end def raise_for_undefined_entity? true end private # set the accessor for the uri, tag_name pair def install_accessor_base(uri, tag_name, accessor_base) @@accessor_bases[uri] ||= {} @@accessor_bases[uri][tag_name] = accessor_base.chomp("=") end def def_get_text_element(uri, element_name, file, line) register_uri(uri, element_name) method_name = "start_#{element_name}" unless private_method_defined?(method_name) define_method(method_name) do |name, prefix, attrs, ns| uri = _ns(ns, prefix) if self.class.uri_registered?(uri, element_name) start_get_text_element(name, prefix, ns, uri) else start_else_element(name, prefix, attrs, ns) end end private(method_name) end end end end module ListenerMixin attr_reader :rss attr_accessor :ignore_unknown_element attr_accessor :do_validate def initialize @rss = nil @ignore_unknown_element = true @do_validate = true @ns_stack = [{"xml" => :xml}] @tag_stack = [[]] @text_stack = [''] @proc_stack = [] @last_element = nil @version = @encoding = @standalone = nil @xml_stylesheets = [] @xml_child_mode = false @xml_element = nil @last_xml_element = nil end # set instance vars for version, encoding, standalone def xmldecl(version, encoding, standalone) @version, @encoding, @standalone = version, encoding, standalone end def instruction(name, content) if name == "xml-stylesheet" params = parse_pi_content(content) if params.has_key?("href") @xml_stylesheets << XMLStyleSheet.new(params) end end end def tag_start(name, attributes) @text_stack.push('') ns = @ns_stack.last.dup attrs = {} attributes.each do |n, v| if /\Axmlns(?:\z|:)/ =~ n ns[$POSTMATCH] = v else attrs[n] = v end end @ns_stack.push(ns) prefix, local = split_name(name) @tag_stack.last.push([_ns(ns, prefix), local]) @tag_stack.push([]) if @xml_child_mode previous = @last_xml_element element_attrs = attributes.dup unless previous ns.each do |ns_prefix, value| next if ns_prefix == "xml" key = ns_prefix.empty? ? "xmlns" : "xmlns:#{ns_prefix}" element_attrs[key] ||= value end end next_element = XML::Element.new(local, prefix.empty? ? nil : prefix, _ns(ns, prefix), element_attrs) previous << next_element if previous @last_xml_element = next_element pr = Proc.new do |text, tags| if previous @last_xml_element = previous else @xml_element = @last_xml_element @last_xml_element = nil end end @proc_stack.push(pr) else if @rss.nil? and respond_to?("initial_start_#{local}", true) __send__("initial_start_#{local}", local, prefix, attrs, ns.dup) elsif respond_to?("start_#{local}", true) __send__("start_#{local}", local, prefix, attrs, ns.dup) else start_else_element(local, prefix, attrs, ns.dup) end end end def tag_end(name) if DEBUG p "end tag #{name}" p @tag_stack end text = @text_stack.pop tags = @tag_stack.pop pr = @proc_stack.pop pr.call(text, tags) unless pr.nil? @ns_stack.pop end def text(data) if @xml_child_mode @last_xml_element << data if @last_xml_element else @text_stack.last << data end end private def _ns(ns, prefix) ns.fetch(prefix, "") end CONTENT_PATTERN = /\s*([^=]+)=(["'])([^\2]+?)\2/ # Extract the first name="value" pair from content. # Works with single quotes according to the constant # CONTENT_PATTERN. Return a Hash. def parse_pi_content(content) params = {} content.scan(CONTENT_PATTERN) do |name, quote, value| params[name] = value end params end def start_else_element(local, prefix, attrs, ns) class_name = self.class.class_name(_ns(ns, prefix), local) current_class = @last_element.class if class_name and (current_class.const_defined?(class_name) or current_class.constants.include?(class_name)) next_class = current_class.const_get(class_name) start_have_something_element(local, prefix, attrs, ns, next_class) else if !@do_validate or @ignore_unknown_element @proc_stack.push(nil) else parent = "ROOT ELEMENT???" if current_class.tag_name parent = current_class.tag_name end raise NotExpectedTagError.new(local, _ns(ns, prefix), parent) end end end NAMESPLIT = /^(?:([\w:][-\w\d.]*):)?([\w:][-\w\d.]*)/ def split_name(name) name =~ NAMESPLIT [$1 || '', $2] end def check_ns(tag_name, prefix, ns, require_uri) unless _ns(ns, prefix) == require_uri if @do_validate raise NSError.new(tag_name, prefix, require_uri) else # Force bind required URI with prefix @ns_stack.last[prefix] = require_uri end end end def start_get_text_element(tag_name, prefix, ns, required_uri) pr = Proc.new do |text, tags| setter = self.class.setter(required_uri, tag_name) if @last_element.respond_to?(setter) if @do_validate getter = self.class.getter(required_uri, tag_name) if @last_element.__send__(getter) raise TooMuchTagError.new(tag_name, @last_element.tag_name) end end @last_element.__send__(setter, text.to_s) else if @do_validate and !@ignore_unknown_element raise NotExpectedTagError.new(tag_name, _ns(ns, prefix), @last_element.tag_name) end end end @proc_stack.push(pr) end def start_have_something_element(tag_name, prefix, attrs, ns, klass) check_ns(tag_name, prefix, ns, klass.required_uri) attributes = collect_attributes(tag_name, prefix, attrs, ns, klass) @proc_stack.push(setup_next_element(tag_name, klass, attributes)) end def collect_attributes(tag_name, prefix, attrs, ns, klass) attributes = {} klass.get_attributes.each do |a_name, a_uri, required, element_name| if a_uri.is_a?(String) or !a_uri.respond_to?(:include?) a_uri = [a_uri] end unless a_uri == [""] for prefix, uri in ns if a_uri.include?(uri) val = attrs["#{prefix}:#{a_name}"] break if val end end end if val.nil? and a_uri.include?("") val = attrs[a_name] end if @do_validate and required and val.nil? unless a_uri.include?("") for prefix, uri in ns if a_uri.include?(uri) a_name = "#{prefix}:#{a_name}" end end end raise MissingAttributeError.new(tag_name, a_name) end attributes[a_name] = val end attributes end def setup_next_element(tag_name, klass, attributes) previous = @last_element next_element = klass.new(@do_validate, attributes) previous.set_next_element(tag_name, next_element) @last_element = next_element @last_element.parent = previous if klass.need_parent? @xml_child_mode = @last_element.have_xml_content? Proc.new do |text, tags| p(@last_element.class) if DEBUG if @xml_child_mode @last_element.content = @xml_element.to_s xml_setter = @last_element.class.xml_setter @last_element.__send__(xml_setter, @xml_element) @xml_element = nil @xml_child_mode = false else if klass.have_content? if @last_element.need_base64_encode? text = Base64.decode64(text.lstrip) end @last_element.content = text end end if @do_validate @last_element.validate_for_stream(tags, @ignore_unknown_element) end @last_element = previous end end end unless const_defined? :AVAILABLE_PARSER_LIBRARIES AVAILABLE_PARSER_LIBRARIES = [ ["rss/xmlparser", :XMLParserParser], ["rss/xmlscanner", :XMLScanParser], ["rss/rexmlparser", :REXMLParser], ] end AVAILABLE_PARSERS = [] AVAILABLE_PARSER_LIBRARIES.each do |lib, parser| begin require lib AVAILABLE_PARSERS.push(const_get(parser)) rescue LoadError end end if AVAILABLE_PARSERS.empty? raise XMLParserNotFound 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/rss/1.0.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/1.0.rb
require "rss/parser" module RSS module RSS10 NSPOOL = {} ELEMENTS = [] def self.append_features(klass) super klass.install_must_call_validator('', ::RSS::URI) end end class RDF < Element include RSS10 include RootElementMixin class << self def required_uri URI end end @tag_name = 'RDF' PREFIX = 'rdf' URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" install_ns('', ::RSS::URI) install_ns(PREFIX, URI) [ ["channel", nil], ["image", "?"], ["item", "+", :children], ["textinput", "?"], ].each do |tag, occurs, type| type ||= :child __send__("install_have_#{type}_element", tag, ::RSS::URI, occurs) end alias_method(:rss_version, :feed_version) def initialize(version=nil, encoding=nil, standalone=nil) super('1.0', version, encoding, standalone) @feed_type = "rss" end def full_name tag_name_with_prefix(PREFIX) end class Li < Element include RSS10 class << self def required_uri URI end end [ ["resource", [URI, ""], true] ].each do |name, uri, required| install_get_attribute(name, uri, required) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end def full_name tag_name_with_prefix(PREFIX) end end class Seq < Element include RSS10 Li = ::RSS::RDF::Li class << self def required_uri URI end end @tag_name = 'Seq' install_have_children_element("li", URI, "*") install_must_call_validator('rdf', ::RSS::RDF::URI) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() @li = args[0] if args[0] end end def full_name tag_name_with_prefix(PREFIX) end def setup_maker(target) lis.each do |li| target << li.resource end end end class Bag < Element include RSS10 Li = ::RSS::RDF::Li class << self def required_uri URI end end @tag_name = 'Bag' install_have_children_element("li", URI, "*") install_must_call_validator('rdf', URI) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() @li = args[0] if args[0] end end def full_name tag_name_with_prefix(PREFIX) end def setup_maker(target) lis.each do |li| target << li.resource end end end class Channel < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["about", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end [ ['title', nil, :text], ['link', nil, :text], ['description', nil, :text], ['image', '?', :have_child], ['items', nil, :have_child], ['textinput', '?', :have_child], ].each do |tag, occurs, type| __send__("install_#{type}_element", tag, ::RSS::URI, occurs) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end private def maker_target(maker) maker.channel end def setup_maker_attributes(channel) channel.about = about end class Image < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["resource", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end end class Textinput < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["resource", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end end class Items < Element include RSS10 Seq = ::RSS::RDF::Seq class << self def required_uri ::RSS::URI end end install_have_child_element("Seq", URI, nil) install_must_call_validator('rdf', URI) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.Seq = args[0] end self.Seq ||= Seq.new end def resources if @Seq @Seq.lis.collect do |li| li.resource end else [] end end end end class Image < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["about", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end %w(title url link).each do |name| install_text_element(name, ::RSS::URI, nil) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end private def maker_target(maker) maker.image end end class Item < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["about", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end [ ["title", nil], ["link", nil], ["description", "?"], ].each do |tag, occurs| install_text_element(tag, ::RSS::URI, occurs) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end private def maker_target(items) if items.respond_to?("items") # For backward compatibility items = items.items end items.new_item end end class Textinput < Element include RSS10 class << self def required_uri ::RSS::URI end end [ ["about", URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{PREFIX}:#{name}") end %w(title description name link).each do |name| install_text_element(name, ::RSS::URI, nil) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] end end private def maker_target(maker) maker.textinput end end end RSS10::ELEMENTS.each do |name| BaseListener.install_get_text_element(URI, name, name) end module ListenerMixin private def initial_start_RDF(tag_name, prefix, attrs, ns) check_ns(tag_name, prefix, ns, RDF::URI) @rss = RDF.new(@version, @encoding, @standalone) @rss.do_validate = @do_validate @rss.xml_stylesheets = @xml_stylesheets @last_element = @rss pr = Proc.new do |text, tags| @rss.validate_for_stream(tags, @ignore_unknown_element) if @do_validate end @proc_stack.push(pr) 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/rss/2.0.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/2.0.rb
require "rss/0.9" module RSS class Rss class Channel [ ["generator"], ["ttl", :integer], ].each do |name, type| install_text_element(name, "", "?", name, type) end [ %w(category categories), ].each do |name, plural_name| install_have_children_element(name, "", "*", name, plural_name) end [ ["image", "?"], ["language", "?"], ].each do |name, occurs| install_model(name, "", occurs) end Category = Item::Category class Item [ ["comments", "?"], ["author", "?"], ].each do |name, occurs| install_text_element(name, "", occurs) end [ ["pubDate", '?'], ].each do |name, occurs| install_date_element(name, "", occurs, name, 'rfc822') end alias date pubDate alias date= pubDate= [ ["guid", '?'], ].each do |name, occurs| install_have_child_element(name, "", occurs) end private alias _setup_maker_element setup_maker_element def setup_maker_element(item) _setup_maker_element(item) @guid.setup_maker(item) if @guid end class Guid < Element include RSS09 [ ["isPermaLink", "", false, :boolean] ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end content_setup def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.isPermaLink = args[0] self.content = args[1] end end alias_method :_PermaLink?, :PermaLink? private :_PermaLink? def PermaLink? perma = _PermaLink? perma or perma.nil? end private def maker_target(item) item.guid end def setup_maker_attributes(guid) guid.isPermaLink = isPermaLink guid.content = content end end end end end RSS09::ELEMENTS.each do |name| BaseListener.install_get_text_element("", name, name) 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/rss/0.9.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/0.9.rb
require "rss/parser" module RSS module RSS09 NSPOOL = {} ELEMENTS = [] def self.append_features(klass) super klass.install_must_call_validator('', "") end end class Rss < Element include RSS09 include RootElementMixin %w(channel).each do |name| install_have_child_element(name, "", nil) end attr_writer :feed_version alias_method(:rss_version, :feed_version) alias_method(:rss_version=, :feed_version=) def initialize(feed_version, version=nil, encoding=nil, standalone=nil) super @feed_type = "rss" end def items if @channel @channel.items else [] end end def image if @channel @channel.image else nil end end def textinput if @channel @channel.textInput else nil end end def setup_maker_elements(maker) super items.each do |item| item.setup_maker(maker.items) end image.setup_maker(maker) if image textinput.setup_maker(maker) if textinput end private def _attrs [ ["version", true, "feed_version"], ] end class Channel < Element include RSS09 [ ["title", nil, :text], ["link", nil, :text], ["description", nil, :text], ["language", nil, :text], ["copyright", "?", :text], ["managingEditor", "?", :text], ["webMaster", "?", :text], ["rating", "?", :text], ["pubDate", "?", :date, :rfc822], ["lastBuildDate", "?", :date, :rfc822], ["docs", "?", :text], ["cloud", "?", :have_attribute], ["skipDays", "?", :have_child], ["skipHours", "?", :have_child], ["image", nil, :have_child], ["item", "*", :have_children], ["textInput", "?", :have_child], ].each do |name, occurs, type, *args| __send__("install_#{type}_element", name, "", occurs, name, *args) end alias date pubDate alias date= pubDate= private def maker_target(maker) maker.channel end def setup_maker_elements(channel) super [ [skipDays, "day"], [skipHours, "hour"], ].each do |skip, key| if skip skip.__send__("#{key}s").each do |val| target_skips = channel.__send__("skip#{key.capitalize}s") new_target = target_skips.__send__("new_#{key}") new_target.content = val.content end end end end def not_need_to_call_setup_maker_variables %w(image textInput) end class SkipDays < Element include RSS09 [ ["day", "*"] ].each do |name, occurs| install_have_children_element(name, "", occurs) end class Day < Element include RSS09 content_setup def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end end end class SkipHours < Element include RSS09 [ ["hour", "*"] ].each do |name, occurs| install_have_children_element(name, "", occurs) end class Hour < Element include RSS09 content_setup(:integer) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end end end class Image < Element include RSS09 %w(url title link).each do |name| install_text_element(name, "", nil) end [ ["width", :integer], ["height", :integer], ["description"], ].each do |name, type| install_text_element(name, "", "?", name, type) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.url = args[0] self.title = args[1] self.link = args[2] self.width = args[3] self.height = args[4] self.description = args[5] end end private def maker_target(maker) maker.image end end class Cloud < Element include RSS09 [ ["domain", "", true], ["port", "", true, :integer], ["path", "", true], ["registerProcedure", "", true], ["protocol", "", true], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.domain = args[0] self.port = args[1] self.path = args[2] self.registerProcedure = args[3] self.protocol = args[4] end end end class Item < Element include RSS09 [ ["title", '?', :text], ["link", '?', :text], ["description", '?', :text], ["category", '*', :have_children, "categories"], ["source", '?', :have_child], ["enclosure", '?', :have_child], ].each do |tag, occurs, type, *args| __send__("install_#{type}_element", tag, "", occurs, tag, *args) end private def maker_target(items) if items.respond_to?("items") # For backward compatibility items = items.items end items.new_item end def setup_maker_element(item) super @enclosure.setup_maker(item) if @enclosure @source.setup_maker(item) if @source end class Source < Element include RSS09 [ ["url", "", true] ].each do |name, uri, required| install_get_attribute(name, uri, required) end content_setup def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.url = args[0] self.content = args[1] end end private def maker_target(item) item.source end def setup_maker_attributes(source) source.url = url source.content = content end end class Enclosure < Element include RSS09 [ ["url", "", true], ["length", "", true, :integer], ["type", "", true], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.url = args[0] self.length = args[1] self.type = args[2] end end private def maker_target(item) item.enclosure end def setup_maker_attributes(enclosure) enclosure.url = url enclosure.length = length enclosure.type = type end end class Category < Element include RSS09 [ ["domain", "", false] ].each do |name, uri, required| install_get_attribute(name, uri, required) end content_setup def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.domain = args[0] self.content = args[1] end end private def maker_target(item) item.new_category end def setup_maker_attributes(category) category.domain = domain category.content = content end end end class TextInput < Element include RSS09 %w(title description name link).each do |name| install_text_element(name, "", nil) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.title = args[0] self.description = args[1] self.name = args[2] self.link = args[3] end end private def maker_target(maker) maker.textinput end end end end RSS09::ELEMENTS.each do |name| BaseListener.install_get_text_element("", name, name) end module ListenerMixin private def initial_start_rss(tag_name, prefix, attrs, ns) check_ns(tag_name, prefix, ns, "") @rss = Rss.new(attrs['version'], @version, @encoding, @standalone) @rss.do_validate = @do_validate @rss.xml_stylesheets = @xml_stylesheets @last_element = @rss pr = Proc.new do |text, tags| @rss.validate_for_stream(tags, @ignore_unknown_element) if @do_validate end @proc_stack.push(pr) 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/rss/atom.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/atom.rb
require 'base64' require 'rss/parser' module RSS module Atom URI = "http://www.w3.org/2005/Atom" XHTML_URI = "http://www.w3.org/1999/xhtml" module CommonModel NSPOOL = {} ELEMENTS = [] def self.append_features(klass) super klass.install_must_call_validator("atom", URI) [ ["lang", :xml], ["base", :xml], ].each do |name, uri, required| klass.install_get_attribute(name, uri, required, [nil, :inherit]) end klass.class_eval do class << self def required_uri URI end def need_parent? true end end end end end module ContentModel module ClassMethods def content_type @content_type ||= nil end end class << self def append_features(klass) super klass.extend(ClassMethods) klass.content_setup(klass.content_type, klass.tag_name) end end def maker_target(target) target end private def setup_maker_element_writer "#{self.class.name.split(/::/).last.downcase}=" end def setup_maker_element(target) target.__send__(setup_maker_element_writer, content) super end end module URIContentModel class << self def append_features(klass) super klass.class_eval do @content_type = [nil, :uri] include(ContentModel) end end end end module TextConstruct def self.append_features(klass) super klass.class_eval do [ ["type", ""], ].each do |name, uri, required| install_get_attribute(name, uri, required, :text_type) end content_setup add_need_initialize_variable("xhtml") class << self def xml_getter "xhtml" end def xml_setter "xhtml=" end end end end attr_writer :xhtml def xhtml return @xhtml if @xhtml.nil? if @xhtml.is_a?(XML::Element) and [@xhtml.name, @xhtml.uri] == ["div", XHTML_URI] return @xhtml end children = @xhtml children = [children] unless children.is_a?(Array) XML::Element.new("div", nil, XHTML_URI, {"xmlns" => XHTML_URI}, children) end def have_xml_content? @type == "xhtml" end def atom_validate(ignore_unknown_element, tags, uri) if have_xml_content? if @xhtml.nil? raise MissingTagError.new("div", tag_name) end unless [@xhtml.name, @xhtml.uri] == ["div", XHTML_URI] raise NotExpectedTagError.new(@xhtml.name, @xhtml.uri, tag_name) end end end private def maker_target(target) target.__send__(self.class.name.split(/::/).last.downcase) {|x| x} end def setup_maker_attributes(target) target.type = type target.content = content target.xml_content = @xhtml end end module PersonConstruct def self.append_features(klass) super klass.class_eval do [ ["name", nil], ["uri", "?"], ["email", "?"], ].each do |tag, occurs| install_have_attribute_element(tag, URI, occurs, nil, :content) end end end def maker_target(target) target.__send__("new_#{self.class.name.split(/::/).last.downcase}") end class Name < RSS::Element include CommonModel include ContentModel end class Uri < RSS::Element include CommonModel include URIContentModel end class Email < RSS::Element include CommonModel include ContentModel end end module DateConstruct def self.append_features(klass) super klass.class_eval do @content_type = :w3cdtf include(ContentModel) end end def atom_validate(ignore_unknown_element, tags, uri) raise NotAvailableValueError.new(tag_name, "") if content.nil? end end module DuplicateLinkChecker def validate_duplicate_links(links) link_infos = {} links.each do |link| rel = link.rel || "alternate" next unless rel == "alternate" key = [link.hreflang, link.type] if link_infos.has_key?(key) raise TooMuchTagError.new("link", tag_name) end link_infos[key] = true end end end class Feed < RSS::Element include RootElementMixin include CommonModel include DuplicateLinkChecker install_ns('', URI) [ ["author", "*", :children], ["category", "*", :children, "categories"], ["contributor", "*", :children], ["generator", "?"], ["icon", "?", nil, :content], ["id", nil, nil, :content], ["link", "*", :children], ["logo", "?"], ["rights", "?"], ["subtitle", "?", nil, :content], ["title", nil, nil, :content], ["updated", nil, nil, :content], ["entry", "*", :children, "entries"], ].each do |tag, occurs, type, *args| type ||= :child __send__("install_have_#{type}_element", tag, URI, occurs, tag, *args) end def initialize(version=nil, encoding=nil, standalone=nil) super("1.0", version, encoding, standalone) @feed_type = "atom" @feed_subtype = "feed" end alias_method :items, :entries def have_author? authors.any? {|author| !author.to_s.empty?} or entries.any? {|entry| entry.have_author?(false)} end private def atom_validate(ignore_unknown_element, tags, uri) unless have_author? raise MissingTagError.new("author", tag_name) end validate_duplicate_links(links) end def have_required_elements? super and have_author? end def maker_target(maker) maker.channel end def setup_maker_element(channel) prev_dc_dates = channel.dc_dates.to_a.dup super channel.about = id.content if id channel.dc_dates.replace(prev_dc_dates) end def setup_maker_elements(channel) super items = channel.maker.items entries.each do |entry| entry.setup_maker(items) end end class Author < RSS::Element include CommonModel include PersonConstruct end class Category < RSS::Element include CommonModel [ ["term", "", true], ["scheme", "", false, [nil, :uri]], ["label", ""], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end private def maker_target(target) target.new_category end end class Contributor < RSS::Element include CommonModel include PersonConstruct end class Generator < RSS::Element include CommonModel include ContentModel [ ["uri", "", false, [nil, :uri]], ["version", ""], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end private def setup_maker_attributes(target) target.generator do |generator| generator.uri = uri if uri generator.version = version if version end end end class Icon < RSS::Element include CommonModel include URIContentModel end class Id < RSS::Element include CommonModel include URIContentModel end class Link < RSS::Element include CommonModel [ ["href", "", true, [nil, :uri]], ["rel", ""], ["type", ""], ["hreflang", ""], ["title", ""], ["length", ""], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end private def maker_target(target) target.new_link end end class Logo < RSS::Element include CommonModel include URIContentModel def maker_target(target) target.maker.image end private def setup_maker_element_writer "url=" end end class Rights < RSS::Element include CommonModel include TextConstruct end class Subtitle < RSS::Element include CommonModel include TextConstruct end class Title < RSS::Element include CommonModel include TextConstruct end class Updated < RSS::Element include CommonModel include DateConstruct end class Entry < RSS::Element include CommonModel include DuplicateLinkChecker [ ["author", "*", :children], ["category", "*", :children, "categories"], ["content", "?", :child], ["contributor", "*", :children], ["id", nil, nil, :content], ["link", "*", :children], ["published", "?", :child, :content], ["rights", "?", :child], ["source", "?"], ["summary", "?", :child], ["title", nil], ["updated", nil, :child, :content], ].each do |tag, occurs, type, *args| type ||= :attribute __send__("install_have_#{type}_element", tag, URI, occurs, tag, *args) end def have_author?(check_parent=true) authors.any? {|author| !author.to_s.empty?} or (check_parent and @parent and @parent.have_author?) or (source and source.have_author?) end private def atom_validate(ignore_unknown_element, tags, uri) unless have_author? raise MissingTagError.new("author", tag_name) end validate_duplicate_links(links) end def have_required_elements? super and have_author? end def maker_target(items) if items.respond_to?("items") # For backward compatibility items = items.items end items.new_item end Author = Feed::Author Category = Feed::Category class Content < RSS::Element include CommonModel class << self def xml_setter "xml=" end def xml_getter "xml" end end [ ["type", ""], ["src", "", false, [nil, :uri]], ].each do |name, uri, required, type| install_get_attribute(name, uri, required, type) end content_setup add_need_initialize_variable("xml") attr_writer :xml def have_xml_content? inline_xhtml? or inline_other_xml? end def xml return @xml unless inline_xhtml? return @xml if @xml.nil? if @xml.is_a?(XML::Element) and [@xml.name, @xml.uri] == ["div", XHTML_URI] return @xml end children = @xml children = [children] unless children.is_a?(Array) XML::Element.new("div", nil, XHTML_URI, {"xmlns" => XHTML_URI}, children) end def xhtml if inline_xhtml? xml else nil end end def atom_validate(ignore_unknown_element, tags, uri) if out_of_line? raise MissingAttributeError.new(tag_name, "type") if @type.nil? unless (content.nil? or content.empty?) raise NotAvailableValueError.new(tag_name, content) end elsif inline_xhtml? if @xml.nil? raise MissingTagError.new("div", tag_name) end unless @xml.name == "div" and @xml.uri == XHTML_URI raise NotExpectedTagError.new(@xml.name, @xml.uri, tag_name) end end end def inline_text? !out_of_line? and [nil, "text", "html"].include?(@type) end def inline_html? return false if out_of_line? @type == "html" or mime_split == ["text", "html"] end def inline_xhtml? !out_of_line? and @type == "xhtml" end def inline_other? return false if out_of_line? media_type, subtype = mime_split return false if media_type.nil? or subtype.nil? true end def inline_other_text? return false unless inline_other? return false if inline_other_xml? media_type, subtype = mime_split return true if "text" == media_type.downcase false end def inline_other_xml? return false unless inline_other? media_type, subtype = mime_split normalized_mime_type = "#{media_type}/#{subtype}".downcase if /(?:\+xml|^xml)$/ =~ subtype or %w(text/xml-external-parsed-entity application/xml-external-parsed-entity application/xml-dtd).find {|x| x == normalized_mime_type} return true end false end def inline_other_base64? inline_other? and !inline_other_text? and !inline_other_xml? end def out_of_line? not @src.nil? end def mime_split media_type = subtype = nil if /\A\s*([a-z]+)\/([a-z\+]+)\s*(?:;.*)?\z/i =~ @type.to_s media_type = $1.downcase subtype = $2.downcase end [media_type, subtype] end def need_base64_encode? inline_other_base64? end private def empty_content? out_of_line? or super end end Contributor = Feed::Contributor Id = Feed::Id Link = Feed::Link class Published < RSS::Element include CommonModel include DateConstruct end Rights = Feed::Rights class Source < RSS::Element include CommonModel [ ["author", "*", :children], ["category", "*", :children, "categories"], ["contributor", "*", :children], ["generator", "?"], ["icon", "?"], ["id", "?", nil, :content], ["link", "*", :children], ["logo", "?"], ["rights", "?"], ["subtitle", "?"], ["title", "?"], ["updated", "?", nil, :content], ].each do |tag, occurs, type, *args| type ||= :attribute __send__("install_have_#{type}_element", tag, URI, occurs, tag, *args) end def have_author? !author.to_s.empty? end Author = Feed::Author Category = Feed::Category Contributor = Feed::Contributor Generator = Feed::Generator Icon = Feed::Icon Id = Feed::Id Link = Feed::Link Logo = Feed::Logo Rights = Feed::Rights Subtitle = Feed::Subtitle Title = Feed::Title Updated = Feed::Updated end class Summary < RSS::Element include CommonModel include TextConstruct end Title = Feed::Title Updated = Feed::Updated end end class Entry < RSS::Element include RootElementMixin include CommonModel include DuplicateLinkChecker [ ["author", "*", :children], ["category", "*", :children, "categories"], ["content", "?"], ["contributor", "*", :children], ["id", nil, nil, :content], ["link", "*", :children], ["published", "?", :child, :content], ["rights", "?"], ["source", "?"], ["summary", "?"], ["title", nil], ["updated", nil, nil, :content], ].each do |tag, occurs, type, *args| type ||= :attribute __send__("install_have_#{type}_element", tag, URI, occurs, tag, *args) end def initialize(version=nil, encoding=nil, standalone=nil) super("1.0", version, encoding, standalone) @feed_type = "atom" @feed_subtype = "entry" end def items [self] end def setup_maker(maker) maker = maker.maker if maker.respond_to?("maker") super(maker) end def have_author? authors.any? {|author| !author.to_s.empty?} or (source and source.have_author?) end private def atom_validate(ignore_unknown_element, tags, uri) unless have_author? raise MissingTagError.new("author", tag_name) end validate_duplicate_links(links) end def have_required_elements? super and have_author? end def maker_target(maker) maker.items.new_item end Author = Feed::Entry::Author Category = Feed::Entry::Category Content = Feed::Entry::Content Contributor = Feed::Entry::Contributor Id = Feed::Entry::Id Link = Feed::Entry::Link Published = Feed::Entry::Published Rights = Feed::Entry::Rights Source = Feed::Entry::Source Summary = Feed::Entry::Summary Title = Feed::Entry::Title Updated = Feed::Entry::Updated end end Atom::CommonModel::ELEMENTS.each do |name| BaseListener.install_get_text_element(Atom::URI, name, "#{name}=") end module ListenerMixin private def initial_start_feed(tag_name, prefix, attrs, ns) check_ns(tag_name, prefix, ns, Atom::URI) @rss = Atom::Feed.new(@version, @encoding, @standalone) @rss.do_validate = @do_validate @rss.xml_stylesheets = @xml_stylesheets @rss.lang = attrs["xml:lang"] @rss.base = attrs["xml:base"] @last_element = @rss pr = Proc.new do |text, tags| @rss.validate_for_stream(tags) if @do_validate end @proc_stack.push(pr) end def initial_start_entry(tag_name, prefix, attrs, ns) check_ns(tag_name, prefix, ns, Atom::URI) @rss = Atom::Entry.new(@version, @encoding, @standalone) @rss.do_validate = @do_validate @rss.xml_stylesheets = @xml_stylesheets @rss.lang = attrs["xml:lang"] @rss.base = attrs["xml:base"] @last_element = @rss pr = Proc.new do |text, tags| @rss.validate_for_stream(tags) if @do_validate end @proc_stack.push(pr) 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/rss/xmlparser.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/xmlparser.rb
begin require "xml/parser" rescue LoadError require "xmlparser" end begin require "xml/encoding-ja" rescue LoadError require "xmlencoding-ja" if defined?(Kconv) module XMLEncoding_ja class SJISHandler include Kconv end end end end module XML class Parser unless defined?(Error) Error = ::XMLParserError end end end module RSS class REXMLLikeXMLParser < ::XML::Parser include ::XML::Encoding_ja def listener=(listener) @listener = listener end def startElement(name, attrs) @listener.tag_start(name, attrs) end def endElement(name) @listener.tag_end(name) end def character(data) @listener.text(data) end def xmlDecl(version, encoding, standalone) @listener.xmldecl(version, encoding, standalone == 1) end def processingInstruction(target, content) @listener.instruction(target, content) end end class XMLParserParser < BaseParser class << self def listener XMLParserListener end end private def _parse begin parser = REXMLLikeXMLParser.new parser.listener = @listener parser.parse(@rss) rescue ::XML::Parser::Error => e raise NotWellFormedError.new(parser.line){e.message} end end end class XMLParserListener < BaseListener include ListenerMixin def xmldecl(version, encoding, standalone) super # Encoding is converted to UTF-8 when XMLParser parses XML. @encoding = 'UTF-8' 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/rss/rss.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/rss.rb
require "time" class Time class << self unless respond_to?(:w3cdtf) def w3cdtf(date) if /\A\s* (-?\d+)-(\d\d)-(\d\d) (?:T (\d\d):(\d\d)(?::(\d\d))? (\.\d+)? (Z|[+-]\d\d:\d\d)?)? \s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8)) datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i] usec = 0 usec = $7.to_f * 1000000 if $7 zone = $8 if zone off = zone_offset(zone, datetime[0]) datetime = apply_offset(*(datetime + [off])) datetime << usec time = Time.utc(*datetime) time.localtime unless zone_utc?(zone) time else datetime << usec Time.local(*datetime) end else raise ArgumentError.new("invalid date: #{date.inspect}") end end end end unless method_defined?(:w3cdtf) def w3cdtf if usec.zero? fraction_digits = 0 else fraction_digits = Math.log10(usec.to_s.sub(/0*$/, '').to_i).floor + 1 end xmlschema(fraction_digits) end end end require "English" require "rss/utils" require "rss/converter" require "rss/xml-stylesheet" module RSS VERSION = "0.2.4" URI = "http://purl.org/rss/1.0/" DEBUG = false class Error < StandardError; end class OverlappedPrefixError < Error attr_reader :prefix def initialize(prefix) @prefix = prefix end end class InvalidRSSError < Error; end class MissingTagError < InvalidRSSError attr_reader :tag, :parent def initialize(tag, parent) @tag, @parent = tag, parent super("tag <#{tag}> is missing in tag <#{parent}>") end end class TooMuchTagError < InvalidRSSError attr_reader :tag, :parent def initialize(tag, parent) @tag, @parent = tag, parent super("tag <#{tag}> is too much in tag <#{parent}>") end end class MissingAttributeError < InvalidRSSError attr_reader :tag, :attribute def initialize(tag, attribute) @tag, @attribute = tag, attribute super("attribute <#{attribute}> is missing in tag <#{tag}>") end end class UnknownTagError < InvalidRSSError attr_reader :tag, :uri def initialize(tag, uri) @tag, @uri = tag, uri super("tag <#{tag}> is unknown in namespace specified by uri <#{uri}>") end end class NotExpectedTagError < InvalidRSSError attr_reader :tag, :uri, :parent def initialize(tag, uri, parent) @tag, @uri, @parent = tag, uri, parent super("tag <{#{uri}}#{tag}> is not expected in tag <#{parent}>") end end # For backward compatibility :X NotExceptedTagError = NotExpectedTagError class NotAvailableValueError < InvalidRSSError attr_reader :tag, :value, :attribute def initialize(tag, value, attribute=nil) @tag, @value, @attribute = tag, value, attribute message = "value <#{value}> of " message << "attribute <#{attribute}> of " if attribute message << "tag <#{tag}> is not available." super(message) end end class UnknownConversionMethodError < Error attr_reader :to, :from def initialize(to, from) @to = to @from = from super("can't convert to #{to} from #{from}.") end end # for backward compatibility UnknownConvertMethod = UnknownConversionMethodError class ConversionError < Error attr_reader :string, :to, :from def initialize(string, to, from) @string = string @to = to @from = from super("can't convert #{@string} to #{to} from #{from}.") end end class NotSetError < Error attr_reader :name, :variables def initialize(name, variables) @name = name @variables = variables super("required variables of #{@name} are not set: #{@variables.join(', ')}") end end class UnsupportedMakerVersionError < Error attr_reader :version def initialize(version) @version = version super("Maker doesn't support version: #{@version}") end end module BaseModel include Utils def install_have_child_element(tag_name, uri, occurs, name=nil, type=nil) name ||= tag_name add_need_initialize_variable(name) install_model(tag_name, uri, occurs, name) writer_type, reader_type = type def_corresponded_attr_writer name, writer_type def_corresponded_attr_reader name, reader_type install_element(name) do |n, elem_name| <<-EOC if @#{n} "\#{@#{n}.to_s(need_convert, indent)}" else '' end EOC end end alias_method(:install_have_attribute_element, :install_have_child_element) def install_have_children_element(tag_name, uri, occurs, name=nil, plural_name=nil) name ||= tag_name plural_name ||= "#{name}s" add_have_children_element(name, plural_name) add_plural_form(name, plural_name) install_model(tag_name, uri, occurs, plural_name, true) def_children_accessor(name, plural_name) install_element(name, "s") do |n, elem_name| <<-EOC rv = [] @#{n}.each do |x| value = "\#{x.to_s(need_convert, indent)}" rv << value if /\\A\\s*\\z/ !~ value end rv.join("\n") EOC end end def install_text_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil) name ||= tag_name disp_name ||= name self::ELEMENTS << name unless self::ELEMENTS.include?(name) add_need_initialize_variable(name) install_model(tag_name, uri, occurs, name) def_corresponded_attr_writer(name, type, disp_name) def_corresponded_attr_reader(name, type || :convert) install_element(name) do |n, elem_name| <<-EOC if respond_to?(:#{n}_content) content = #{n}_content else content = @#{n} end if content rv = "\#{indent}<#{elem_name}>" value = html_escape(content) if need_convert rv << convert(value) else rv << value end rv << "</#{elem_name}>" rv else '' end EOC end end def install_date_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil) name ||= tag_name type ||= :w3cdtf disp_name ||= name self::ELEMENTS << name add_need_initialize_variable(name) install_model(tag_name, uri, occurs, name) # accessor convert_attr_reader name date_writer(name, type, disp_name) install_element(name) do |n, elem_name| <<-EOC if @#{n} rv = "\#{indent}<#{elem_name}>" value = html_escape(@#{n}.#{type}) if need_convert rv << convert(value) else rv << value end rv << "</#{elem_name}>" rv else '' end EOC end end private def install_element(name, postfix="") elem_name = name.sub('_', ':') method_name = "#{name}_element#{postfix}" add_to_element_method(method_name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{method_name}(need_convert=true, indent='') #{yield(name, elem_name)} end private :#{method_name} EOC end def inherit_convert_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{attr}_without_inherit convert(@#{attr}) end def #{attr} if @#{attr} #{attr}_without_inherit elsif @parent @parent.#{attr} else nil end end EOC end end def uri_convert_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{attr}_without_base convert(@#{attr}) end def #{attr} value = #{attr}_without_base return nil if value.nil? if /\\A[a-z][a-z0-9+.\\-]*:/i =~ value value else "\#{base}\#{value}" end end EOC end end def convert_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{attr} convert(@#{attr}) end EOC end end def yes_clean_other_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, __FILE__, __LINE__ + 1) attr_reader(:#{attr}) def #{attr}? YesCleanOther.parse(@#{attr}) end EOC end end def yes_other_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, __FILE__, __LINE__ + 1) attr_reader(:#{attr}) def #{attr}? Utils::YesOther.parse(@#{attr}) end EOC end end def csv_attr_reader(*attrs) separator = nil if attrs.last.is_a?(Hash) options = attrs.pop separator = options[:separator] end separator ||= ", " attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, __FILE__, __LINE__ + 1) attr_reader(:#{attr}) def #{attr}_content if @#{attr}.nil? @#{attr} else @#{attr}.join(#{separator.dump}) end end EOC end end def date_writer(name, type, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value elsif new_value.kind_of?(Time) @#{name} = new_value.dup else if @do_validate begin @#{name} = Time.__send__('#{type}', new_value) rescue ArgumentError raise NotAvailableValueError.new('#{disp_name}', new_value) end else @#{name} = nil if /\\A\\s*\\z/ !~ new_value.to_s begin unless Date._parse(new_value, false).empty? @#{name} = Time.parse(new_value) end rescue ArgumentError end end end end # Is it need? if @#{name} class << @#{name} undef_method(:to_s) alias_method(:to_s, :#{type}) end end end EOC end def integer_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value else if @do_validate begin @#{name} = Integer(new_value) rescue ArgumentError raise NotAvailableValueError.new('#{disp_name}', new_value) end else @#{name} = new_value.to_i end end end EOC end def positive_integer_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value else if @do_validate begin tmp = Integer(new_value) raise ArgumentError if tmp <= 0 @#{name} = tmp rescue ArgumentError raise NotAvailableValueError.new('#{disp_name}', new_value) end else @#{name} = new_value.to_i end end end EOC end def boolean_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value else if @do_validate and ![true, false, "true", "false"].include?(new_value) raise NotAvailableValueError.new('#{disp_name}', new_value) end if [true, false].include?(new_value) @#{name} = new_value else @#{name} = new_value == "true" end end end EOC end def text_type_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if @do_validate and !["text", "html", "xhtml", nil].include?(new_value) raise NotAvailableValueError.new('#{disp_name}', new_value) end @#{name} = new_value end EOC end def content_writer(name, disp_name=name) klass_name = "self.class::#{Utils.to_class_name(name)}" module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.is_a?(#{klass_name}) @#{name} = new_value else @#{name} = #{klass_name}.new @#{name}.content = new_value end end EOC end def yes_clean_other_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(value) value = (value ? "yes" : "no") if [true, false].include?(value) @#{name} = value end EOC end def yes_other_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(new_value) if [true, false].include?(new_value) new_value = new_value ? "yes" : "no" end @#{name} = new_value end EOC end def csv_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(new_value) @#{name} = Utils::CSV.parse(new_value) end EOC end def csv_integer_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(new_value) @#{name} = Utils::CSV.parse(new_value) {|v| Integer(v)} end EOC end def def_children_accessor(accessor_name, plural_name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{plural_name} @#{accessor_name} end def #{accessor_name}(*args) if args.empty? @#{accessor_name}.first else @#{accessor_name}[*args] end end def #{accessor_name}=(*args) receiver = self.class.name warn("Warning:\#{caller.first.sub(/:in `.*'\z/, '')}: " \ "Don't use `\#{receiver}\##{accessor_name} = XXX'/" \ "`\#{receiver}\#set_#{accessor_name}(XXX)'. " \ "Those APIs are not sense of Ruby. " \ "Use `\#{receiver}\##{plural_name} << XXX' instead of them.") if args.size == 1 @#{accessor_name}.push(args[0]) else @#{accessor_name}.__send__("[]=", *args) end end alias_method(:set_#{accessor_name}, :#{accessor_name}=) EOC end end module SetupMaker def setup_maker(maker) target = maker_target(maker) unless target.nil? setup_maker_attributes(target) setup_maker_element(target) setup_maker_elements(target) end end private def maker_target(maker) nil end def setup_maker_attributes(target) end def setup_maker_element(target) self.class.need_initialize_variables.each do |var| value = __send__(var) next if value.nil? if value.respond_to?("setup_maker") and !not_need_to_call_setup_maker_variables.include?(var) value.setup_maker(target) else setter = "#{var}=" if target.respond_to?(setter) target.__send__(setter, value) end end end end def not_need_to_call_setup_maker_variables [] end def setup_maker_elements(parent) self.class.have_children_elements.each do |name, plural_name| if parent.respond_to?(plural_name) target = parent.__send__(plural_name) __send__(plural_name).each do |elem| elem.setup_maker(target) end end end end end class Element extend BaseModel include Utils extend Utils::InheritedReader include SetupMaker INDENT = " " MUST_CALL_VALIDATORS = {} MODELS = [] GET_ATTRIBUTES = [] HAVE_CHILDREN_ELEMENTS = [] TO_ELEMENT_METHODS = [] NEED_INITIALIZE_VARIABLES = [] PLURAL_FORMS = {} class << self def must_call_validators inherited_hash_reader("MUST_CALL_VALIDATORS") end def models inherited_array_reader("MODELS") end def get_attributes inherited_array_reader("GET_ATTRIBUTES") end def have_children_elements inherited_array_reader("HAVE_CHILDREN_ELEMENTS") end def to_element_methods inherited_array_reader("TO_ELEMENT_METHODS") end def need_initialize_variables inherited_array_reader("NEED_INITIALIZE_VARIABLES") end def plural_forms inherited_hash_reader("PLURAL_FORMS") end def inherited_base ::RSS::Element end def inherited(klass) klass.const_set("MUST_CALL_VALIDATORS", {}) klass.const_set("MODELS", []) klass.const_set("GET_ATTRIBUTES", []) klass.const_set("HAVE_CHILDREN_ELEMENTS", []) klass.const_set("TO_ELEMENT_METHODS", []) klass.const_set("NEED_INITIALIZE_VARIABLES", []) klass.const_set("PLURAL_FORMS", {}) tag_name = klass.name.split(/::/).last tag_name[0, 1] = tag_name[0, 1].downcase klass.instance_variable_set("@tag_name", tag_name) klass.instance_variable_set("@have_content", false) end def install_must_call_validator(prefix, uri) self::MUST_CALL_VALIDATORS[uri] = prefix end def install_model(tag, uri, occurs=nil, getter=nil, plural=false) getter ||= tag if m = self::MODELS.find {|t, u, o, g, p| t == tag and u == uri} m[2] = occurs else self::MODELS << [tag, uri, occurs, getter, plural] end end def install_get_attribute(name, uri, required=true, type=nil, disp_name=nil, element_name=nil) disp_name ||= name element_name ||= name writer_type, reader_type = type def_corresponded_attr_writer name, writer_type, disp_name def_corresponded_attr_reader name, reader_type if type == :boolean and /^is/ =~ name alias_method "#{$POSTMATCH}?", name end self::GET_ATTRIBUTES << [name, uri, required, element_name] add_need_initialize_variable(disp_name) end def def_corresponded_attr_writer(name, type=nil, disp_name=nil) disp_name ||= name case type when :integer integer_writer name, disp_name when :positive_integer positive_integer_writer name, disp_name when :boolean boolean_writer name, disp_name when :w3cdtf, :rfc822, :rfc2822 date_writer name, type, disp_name when :text_type text_type_writer name, disp_name when :content content_writer name, disp_name when :yes_clean_other yes_clean_other_writer name, disp_name when :yes_other yes_other_writer name, disp_name when :csv csv_writer name when :csv_integer csv_integer_writer name else attr_writer name end end def def_corresponded_attr_reader(name, type=nil) case type when :inherit inherit_convert_attr_reader name when :uri uri_convert_attr_reader name when :yes_clean_other yes_clean_other_attr_reader name when :yes_other yes_other_attr_reader name when :csv csv_attr_reader name when :csv_integer csv_attr_reader name, :separator => "," else convert_attr_reader name end end def content_setup(type=nil, disp_name=nil) writer_type, reader_type = type def_corresponded_attr_writer :content, writer_type, disp_name def_corresponded_attr_reader :content, reader_type @have_content = true end def have_content? @have_content end def add_have_children_element(variable_name, plural_name) self::HAVE_CHILDREN_ELEMENTS << [variable_name, plural_name] end def add_to_element_method(method_name) self::TO_ELEMENT_METHODS << method_name end def add_need_initialize_variable(variable_name) self::NEED_INITIALIZE_VARIABLES << variable_name end def add_plural_form(singular, plural) self::PLURAL_FORMS[singular] = plural end def required_prefix nil end def required_uri "" end def need_parent? false end def install_ns(prefix, uri) if self::NSPOOL.has_key?(prefix) raise OverlappedPrefixError.new(prefix) end self::NSPOOL[prefix] = uri end def tag_name @tag_name end end attr_accessor :parent, :do_validate def initialize(do_validate=true, attrs=nil) @parent = nil @converter = nil if attrs.nil? and (do_validate.is_a?(Hash) or do_validate.is_a?(Array)) do_validate, attrs = true, do_validate end @do_validate = do_validate initialize_variables(attrs || {}) end def tag_name self.class.tag_name end def full_name tag_name end def converter=(converter) @converter = converter targets = children.dup self.class.have_children_elements.each do |variable_name, plural_name| targets.concat(__send__(plural_name)) end targets.each do |target| target.converter = converter unless target.nil? end end def convert(value) if @converter @converter.convert(value) else value end end def valid?(ignore_unknown_element=true) validate(ignore_unknown_element) true rescue RSS::Error false end def validate(ignore_unknown_element=true) do_validate = @do_validate @do_validate = true validate_attribute __validate(ignore_unknown_element) ensure @do_validate = do_validate end def validate_for_stream(tags, ignore_unknown_element=true) validate_attribute __validate(ignore_unknown_element, tags, false) end def to_s(need_convert=true, indent='') if self.class.have_content? return "" if !empty_content? and !content_is_set? rv = tag(indent) do |next_indent| if empty_content? "" else xmled_content end end else rv = tag(indent) do |next_indent| self.class.to_element_methods.collect do |method_name| __send__(method_name, false, next_indent) end end end rv = convert(rv) if need_convert rv end def have_xml_content? false end def need_base64_encode? false end def set_next_element(tag_name, next_element) klass = next_element.class prefix = "" prefix << "#{klass.required_prefix}_" if klass.required_prefix key = "#{prefix}#{tag_name.gsub(/-/, '_')}" if self.class.plural_forms.has_key?(key) ary = __send__("#{self.class.plural_forms[key]}") ary << next_element else __send__("#{key}=", next_element) end end protected def have_required_elements? self.class::MODELS.all? do |tag, uri, occurs, getter| if occurs.nil? or occurs == "+" child = __send__(getter) if child.is_a?(Array) children = child children.any? {|c| c.have_required_elements?} else !child.to_s.empty? end else true end end end private def initialize_variables(attrs) normalized_attrs = {} attrs.each do |key, value| normalized_attrs[key.to_s] = value end self.class.need_initialize_variables.each do |variable_name| value = normalized_attrs[variable_name.to_s] if value __send__("#{variable_name}=", value) else instance_variable_set("@#{variable_name}", nil) end end initialize_have_children_elements @content = normalized_attrs["content"] if self.class.have_content? end def initialize_have_children_elements self.class.have_children_elements.each do |variable_name, plural_name| instance_variable_set("@#{variable_name}", []) end end def tag(indent, additional_attrs={}, &block) next_indent = indent + INDENT attrs = collect_attrs return "" if attrs.nil? return "" unless have_required_elements? attrs.update(additional_attrs) start_tag = make_start_tag(indent, next_indent, attrs.dup) if block content = block.call(next_indent) else content = [] end if content.is_a?(String) content = [content] start_tag << ">" end_tag = "</#{full_name}>" else content = content.reject{|x| x.empty?} if content.empty? return "" if attrs.empty? end_tag = "/>" else start_tag << ">\n" end_tag = "\n#{indent}</#{full_name}>" end end start_tag + content.join("\n") + end_tag end def make_start_tag(indent, next_indent, attrs) start_tag = ["#{indent}<#{full_name}"] unless attrs.empty? start_tag << attrs.collect do |key, value| %Q[#{h key}="#{h value}"] end.join("\n#{next_indent}") end start_tag.join(" ") end def collect_attrs attrs = {} _attrs.each do |name, required, alias_name| value = __send__(alias_name || name) return nil if required and value.nil? next if value.nil? return nil if attrs.has_key?(name) attrs[name] = value end attrs end def tag_name_with_prefix(prefix) "#{prefix}:#{tag_name}" end # For backward compatibility def calc_indent '' end def children rv = [] self.class.models.each do |name, uri, occurs, getter| value = __send__(getter) next if value.nil? value = [value] unless value.is_a?(Array) value.each do |v| rv << v if v.is_a?(Element) end end rv end def _tags rv = [] self.class.models.each do |name, uri, occurs, getter, plural| value = __send__(getter) next if value.nil? if plural and value.is_a?(Array) rv.concat([[uri, name]] * value.size) else rv << [uri, name] end end rv end def _attrs self.class.get_attributes.collect do |name, uri, required, element_name| [element_name, required, name] end end def __validate(ignore_unknown_element, tags=_tags, recursive=true) if recursive children.compact.each do |child| child.validate end end must_call_validators = self.class.must_call_validators tags = tag_filter(tags.dup) p tags if DEBUG must_call_validators.each do |uri, prefix| _validate(ignore_unknown_element, tags[uri], uri) meth = "#{prefix}_validate" if !prefix.empty? and respond_to?(meth, true) __send__(meth, ignore_unknown_element, tags[uri], uri) end end end def validate_attribute _attrs.each do |a_name, required, alias_name| value = instance_variable_get("@#{alias_name || a_name}") if required and value.nil? raise MissingAttributeError.new(tag_name, a_name) end __send__("#{alias_name || a_name}=", value) end end def _validate(ignore_unknown_element, tags, uri, models=self.class.models) count = 1 do_redo = false not_shift = false tag = nil models = models.find_all {|model| model[1] == uri} element_names = models.collect {|model| model[0]} if tags tags_size = tags.size tags = tags.sort_by {|x| element_names.index(x) || tags_size} end _tags = tags.dup if tags models.each_with_index do |model, i| name, model_uri, occurs, getter = model if DEBUG p "before" p tags p model end if not_shift not_shift = false elsif tags tag = tags.shift end if DEBUG p "mid" p count end case occurs when '?' if count > 2 raise TooMuchTagError.new(name, tag_name) else if name == tag do_redo = true else not_shift = true end end when '*' if name == tag do_redo = true else not_shift = true end when '+' if name == tag do_redo = true else if count > 1 not_shift = true else raise MissingTagError.new(name, tag_name) end end else if name == tag if models[i+1] and models[i+1][0] != name and tags and tags.first == name raise TooMuchTagError.new(name, tag_name) end else raise MissingTagError.new(name, tag_name) end end if DEBUG p "after" p not_shift p do_redo p tag end if do_redo do_redo = false count += 1 redo else count = 1 end end if !ignore_unknown_element and !tags.nil? and !tags.empty? raise NotExpectedTagError.new(tags.first, uri, tag_name) end end def tag_filter(tags) rv = {} tags.each do |tag| rv[tag[0]] = [] unless rv.has_key?(tag[0]) rv[tag[0]].push(tag[1]) end rv end def empty_content? false end def content_is_set? if have_xml_content? __send__(self.class.xml_getter) else content end end def xmled_content if have_xml_content? __send__(self.class.xml_getter).to_s else _content = content _content = Base64.encode64(_content) if need_base64_encode? h(_content) end end end module RootElementMixin include XMLStyleSheetMixin attr_reader :output_encoding attr_reader :feed_type, :feed_subtype, :feed_version attr_accessor :version, :encoding, :standalone def initialize(feed_version, version=nil, encoding=nil, standalone=nil) super() @feed_type = nil @feed_subtype = nil @feed_version = feed_version @version = version || '1.0' @encoding = encoding @standalone = standalone @output_encoding = nil end def feed_info [@feed_type, @feed_version, @feed_subtype] end def output_encoding=(enc) @output_encoding = enc self.converter = Converter.new(@output_encoding, @encoding) end def setup_maker(maker) maker.version = version maker.encoding = encoding maker.standalone = standalone xml_stylesheets.each do |xss| xss.setup_maker(maker) end super end def to_feed(type, &block) Maker.make(type) do |maker| setup_maker(maker) block.call(maker) if block end end def to_rss(type, &block) to_feed("rss#{type}", &block) end def to_atom(type, &block) to_feed("atom:#{type}", &block) end def to_xml(type=nil, &block) if type.nil? or same_feed_type?(type) to_s else
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
true
ThoughtWorksStudios/oauth2_provider
https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/1.8/rss/xml-stylesheet.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/xml-stylesheet.rb
require "rss/utils" module RSS module XMLStyleSheetMixin attr_accessor :xml_stylesheets def initialize(*args) super @xml_stylesheets = [] end private def xml_stylesheet_pi xsss = @xml_stylesheets.collect do |xss| pi = xss.to_s pi = nil if /\A\s*\z/ =~ pi pi end.compact xsss.push("") unless xsss.empty? xsss.join("\n") end end class XMLStyleSheet include Utils ATTRIBUTES = %w(href type title media charset alternate) GUESS_TABLE = { "xsl" => "text/xsl", "css" => "text/css", } attr_accessor(*ATTRIBUTES) attr_accessor(:do_validate) def initialize(*attrs) if attrs.size == 1 and (attrs.first.is_a?(Hash) or attrs.first.is_a?(Array)) attrs = attrs.first end @do_validate = true ATTRIBUTES.each do |attr| __send__("#{attr}=", nil) end vars = ATTRIBUTES.dup vars.unshift(:do_validate) attrs.each do |name, value| if vars.include?(name.to_s) __send__("#{name}=", value) end end end def to_s rv = "" if @href rv << %Q[<?xml-stylesheet] ATTRIBUTES.each do |name| if __send__(name) rv << %Q[ #{name}="#{h __send__(name)}"] end end rv << %Q[?>] end rv end remove_method(:href=) def href=(value) @href = value if @href and @type.nil? @type = guess_type(@href) end @href end remove_method(:alternate=) def alternate=(value) if value.nil? or /\A(?:yes|no)\z/ =~ value @alternate = value else if @do_validate args = ["?xml-stylesheet?", %Q[alternate="#{value}"]] raise NotAvailableValueError.new(*args) end end @alternate end def setup_maker(maker) xss = maker.xml_stylesheets.new_xml_stylesheet ATTRIBUTES.each do |attr| xss.__send__("#{attr}=", __send__(attr)) end end private def guess_type(filename) /\.([^.]+)$/ =~ filename GUESS_TABLE[$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/rss/slash.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/slash.rb
require 'rss/1.0' module RSS SLASH_PREFIX = 'slash' SLASH_URI = "http://purl.org/rss/1.0/modules/slash/" RDF.install_ns(SLASH_PREFIX, SLASH_URI) module SlashModel extend BaseModel ELEMENT_INFOS = \ [ ["section"], ["department"], ["comments", :positive_integer], ["hit_parade", :csv_integer], ] class << self def append_features(klass) super return if klass.instance_of?(Module) klass.install_must_call_validator(SLASH_PREFIX, SLASH_URI) ELEMENT_INFOS.each do |name, type, *additional_infos| full_name = "#{SLASH_PREFIX}_#{name}" klass.install_text_element(full_name, SLASH_URI, "?", full_name, type, name) end klass.module_eval do alias_method(:slash_hit_parades, :slash_hit_parade) undef_method(:slash_hit_parade) alias_method(:slash_hit_parade, :slash_hit_parade_content) end end end end class RDF class Item; include SlashModel; end end SlashModel::ELEMENT_INFOS.each do |name, type| accessor_base = "#{SLASH_PREFIX}_#{name}" BaseListener.install_get_text_element(SLASH_URI, name, accessor_base) 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/rss/dublincore.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/dublincore.rb
require "rss/rss" module RSS DC_PREFIX = 'dc' DC_URI = "http://purl.org/dc/elements/1.1/" module BaseDublinCoreModel def append_features(klass) super return if klass.instance_of?(Module) DublinCoreModel::ELEMENT_NAME_INFOS.each do |name, plural_name| plural = plural_name || "#{name}s" full_name = "#{DC_PREFIX}_#{name}" full_plural_name = "#{DC_PREFIX}_#{plural}" klass_name = "DublinCore#{Utils.to_class_name(name)}" klass.install_must_call_validator(DC_PREFIX, DC_URI) klass.install_have_children_element(name, DC_URI, "*", full_name, full_plural_name) klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0)) remove_method :#{full_name} remove_method :#{full_name}= remove_method :set_#{full_name} def #{full_name} @#{full_name}.first and @#{full_name}.first.value end def #{full_name}=(new_value) @#{full_name}[0] = Utils.new_with_value_if_need(#{klass_name}, new_value) end alias set_#{full_name} #{full_name}= EOC end klass.module_eval(<<-EOC, *get_file_and_line_from_caller(0)) if method_defined?(:date) alias date_without_#{DC_PREFIX}_date= date= def date=(value) self.date_without_#{DC_PREFIX}_date = value self.#{DC_PREFIX}_date = value end else alias date #{DC_PREFIX}_date alias date= #{DC_PREFIX}_date= end # For backward compatibility alias #{DC_PREFIX}_rightses #{DC_PREFIX}_rights_list EOC end end module DublinCoreModel extend BaseModel extend BaseDublinCoreModel TEXT_ELEMENTS = { "title" => nil, "description" => nil, "creator" => nil, "subject" => nil, "publisher" => nil, "contributor" => nil, "type" => nil, "format" => nil, "identifier" => nil, "source" => nil, "language" => nil, "relation" => nil, "coverage" => nil, "rights" => "rights_list" } DATE_ELEMENTS = { "date" => "w3cdtf", } ELEMENT_NAME_INFOS = DublinCoreModel::TEXT_ELEMENTS.to_a DublinCoreModel::DATE_ELEMENTS.each do |name, | ELEMENT_NAME_INFOS << [name, nil] end ELEMENTS = TEXT_ELEMENTS.keys + DATE_ELEMENTS.keys ELEMENTS.each do |name, plural_name| module_eval(<<-EOC, *get_file_and_line_from_caller(0)) class DublinCore#{Utils.to_class_name(name)} < Element include RSS10 content_setup class << self def required_prefix DC_PREFIX end def required_uri DC_URI end end @tag_name = #{name.dump} alias_method(:value, :content) alias_method(:value=, :content=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end def full_name tag_name_with_prefix(DC_PREFIX) end def maker_target(target) target.new_#{name} end def setup_maker_attributes(#{name}) #{name}.content = content end end EOC end DATE_ELEMENTS.each do |name, type| tag_name = "#{DC_PREFIX}:#{name}" module_eval(<<-EOC, *get_file_and_line_from_caller(0)) class DublinCore#{Utils.to_class_name(name)} < Element remove_method(:content=) remove_method(:value=) date_writer("content", #{type.dump}, #{tag_name.dump}) alias_method(:value=, :content=) end EOC end end # For backward compatibility DublincoreModel = DublinCoreModel DublinCoreModel::ELEMENTS.each do |name| class_name = Utils.to_class_name(name) BaseListener.install_class_name(DC_URI, name, "DublinCore#{class_name}") end DublinCoreModel::ELEMENTS.collect! {|name| "#{DC_PREFIX}_#{name}"} end require 'rss/dublincore/1.0' require 'rss/dublincore/2.0' require 'rss/dublincore/atom'
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/rss/itunes.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/itunes.rb
require 'rss/2.0' module RSS ITUNES_PREFIX = 'itunes' ITUNES_URI = 'http://www.itunes.com/dtds/podcast-1.0.dtd' Rss.install_ns(ITUNES_PREFIX, ITUNES_URI) module ITunesModelUtils include Utils def def_class_accessor(klass, name, type, *args) normalized_name = name.gsub(/-/, "_") full_name = "#{ITUNES_PREFIX}_#{normalized_name}" klass_name = "ITunes#{Utils.to_class_name(normalized_name)}" case type when :element, :attribute klass::ELEMENTS << full_name def_element_class_accessor(klass, name, full_name, klass_name, *args) when :elements klass::ELEMENTS << full_name def_elements_class_accessor(klass, name, full_name, klass_name, *args) else klass.install_must_call_validator(ITUNES_PREFIX, ITUNES_URI) klass.install_text_element(normalized_name, ITUNES_URI, "?", full_name, type, name) end end def def_element_class_accessor(klass, name, full_name, klass_name, recommended_attribute_name=nil) klass.install_have_child_element(name, ITUNES_PREFIX, "?", full_name) end def def_elements_class_accessor(klass, name, full_name, klass_name, plural_name, recommended_attribute_name=nil) full_plural_name = "#{ITUNES_PREFIX}_#{plural_name}" klass.install_have_children_element(name, ITUNES_PREFIX, "*", full_name, full_plural_name) end end module ITunesBaseModel extend ITunesModelUtils ELEMENTS = [] ELEMENT_INFOS = [["author"], ["block", :yes_other], ["explicit", :yes_clean_other], ["keywords", :csv], ["subtitle"], ["summary"]] end module ITunesChannelModel extend BaseModel extend ITunesModelUtils include ITunesBaseModel ELEMENTS = [] class << self def append_features(klass) super return if klass.instance_of?(Module) ELEMENT_INFOS.each do |name, type, *additional_infos| def_class_accessor(klass, name, type, *additional_infos) end end end ELEMENT_INFOS = [ ["category", :elements, "categories", "text"], ["image", :attribute, "href"], ["owner", :element], ["new-feed-url"], ] + ITunesBaseModel::ELEMENT_INFOS class ITunesCategory < Element include RSS09 @tag_name = "category" class << self def required_prefix ITUNES_PREFIX end def required_uri ITUNES_URI end end [ ["text", "", true] ].each do |name, uri, required| install_get_attribute(name, uri, required) end ITunesCategory = self install_have_children_element("category", ITUNES_URI, "*", "#{ITUNES_PREFIX}_category", "#{ITUNES_PREFIX}_categories") def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.text = args[0] end end def full_name tag_name_with_prefix(ITUNES_PREFIX) end private def maker_target(categories) if text or !itunes_categories.empty? categories.new_category else nil end end def setup_maker_attributes(category) category.text = text if text end def setup_maker_elements(category) super(category) itunes_categories.each do |sub_category| sub_category.setup_maker(category) end end end class ITunesImage < Element include RSS09 @tag_name = "image" class << self def required_prefix ITUNES_PREFIX end def required_uri ITUNES_URI end end [ ["href", "", true] ].each do |name, uri, required| install_get_attribute(name, uri, required) end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.href = args[0] end end def full_name tag_name_with_prefix(ITUNES_PREFIX) end private def maker_target(target) if href target.itunes_image {|image| image} else nil end end def setup_maker_attributes(image) image.href = href end end class ITunesOwner < Element include RSS09 @tag_name = "owner" class << self def required_prefix ITUNES_PREFIX end def required_uri ITUNES_URI end end install_must_call_validator(ITUNES_PREFIX, ITUNES_URI) [ ["name"], ["email"], ].each do |name,| ITunesBaseModel::ELEMENT_INFOS << name install_text_element(name, ITUNES_URI, nil, "#{ITUNES_PREFIX}_#{name}") end def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.itunes_name = args[0] self.itunes_email = args[1] end end def full_name tag_name_with_prefix(ITUNES_PREFIX) end private def maker_target(target) target.itunes_owner end def setup_maker_element(owner) super(owner) owner.itunes_name = itunes_name owner.itunes_email = itunes_email end end end module ITunesItemModel extend BaseModel extend ITunesModelUtils include ITunesBaseModel class << self def append_features(klass) super return if klass.instance_of?(Module) ELEMENT_INFOS.each do |name, type| def_class_accessor(klass, name, type) end end end ELEMENT_INFOS = ITunesBaseModel::ELEMENT_INFOS + [["duration", :element, "content"]] class ITunesDuration < Element include RSS09 @tag_name = "duration" class << self def required_prefix ITUNES_PREFIX end def required_uri ITUNES_URI end def parse(duration, do_validate=true) if do_validate and /\A(?: \d?\d:[0-5]\d:[0-5]\d| [0-5]?\d:[0-5]\d )\z/x !~ duration raise ArgumentError, "must be one of HH:MM:SS, H:MM:SS, MM::SS, M:SS: " + duration.inspect end components = duration.split(':') components[3..-1] = nil if components.size > 3 components.unshift("00") until components.size == 3 components.collect do |component| component.to_i end end def construct(hour, minute, second) components = [minute, second] if components.include?(nil) nil else components.unshift(hour) if hour and hour > 0 components.collect do |component| "%02d" % component end.join(":") end end end content_setup alias_method(:value, :content) remove_method(:content=) attr_reader :hour, :minute, :second def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() args = args[0] if args.size == 1 and args[0].is_a?(Array) if args.size == 1 self.content = args[0] elsif args.size > 3 raise ArgumentError, "must be (do_validate, params), (content), " + "(minute, second), ([minute, second]), " + "(hour, minute, second) or ([hour, minute, second]): " + args.inspect else @second, @minute, @hour = args.reverse update_content end end end def content=(value) if value.nil? @content = nil elsif value.is_a?(self.class) self.content = value.content else begin @hour, @minute, @second = self.class.parse(value, @do_validate) rescue ArgumentError raise NotAvailableValueError.new(tag_name, value) end @content = value end end alias_method(:value=, :content=) def hour=(hour) @hour = @do_validate ? Integer(hour) : hour.to_i update_content hour end def minute=(minute) @minute = @do_validate ? Integer(minute) : minute.to_i update_content minute end def second=(second) @second = @do_validate ? Integer(second) : second.to_i update_content second end def full_name tag_name_with_prefix(ITUNES_PREFIX) end private def update_content @content = self.class.construct(hour, minute, second) end def maker_target(target) if @content target.itunes_duration {|duration| duration} else nil end end def setup_maker_element(duration) super(duration) duration.content = @content end end end class Rss class Channel include ITunesChannelModel class Item; include ITunesItemModel; end end end element_infos = ITunesChannelModel::ELEMENT_INFOS + ITunesItemModel::ELEMENT_INFOS element_infos.each do |name, type| case type when :element, :elements, :attribute class_name = Utils.to_class_name(name) BaseListener.install_class_name(ITUNES_URI, name, "ITunes#{class_name}") else accessor_base = "#{ITUNES_PREFIX}_#{name.gsub(/-/, '_')}" BaseListener.install_get_text_element(ITUNES_URI, name, accessor_base) 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/rss/image.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/image.rb
require 'rss/1.0' require 'rss/dublincore' module RSS IMAGE_PREFIX = 'image' IMAGE_URI = 'http://purl.org/rss/1.0/modules/image/' RDF.install_ns(IMAGE_PREFIX, IMAGE_URI) IMAGE_ELEMENTS = [] %w(item favicon).each do |name| class_name = Utils.to_class_name(name) BaseListener.install_class_name(IMAGE_URI, name, "Image#{class_name}") IMAGE_ELEMENTS << "#{IMAGE_PREFIX}_#{name}" end module ImageModelUtils def validate_one_tag_name(ignore_unknown_element, name, tags) if !ignore_unknown_element invalid = tags.find {|tag| tag != name} raise UnknownTagError.new(invalid, IMAGE_URI) if invalid end raise TooMuchTagError.new(name, tag_name) if tags.size > 1 end end module ImageItemModel include ImageModelUtils extend BaseModel def self.append_features(klass) super klass.install_have_child_element("item", IMAGE_URI, "?", "#{IMAGE_PREFIX}_item") klass.install_must_call_validator(IMAGE_PREFIX, IMAGE_URI) end class ImageItem < Element include RSS10 include DublinCoreModel @tag_name = "item" class << self def required_prefix IMAGE_PREFIX end def required_uri IMAGE_URI end end install_must_call_validator(IMAGE_PREFIX, IMAGE_URI) [ ["about", ::RSS::RDF::URI, true], ["resource", ::RSS::RDF::URI, false], ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{::RSS::RDF::PREFIX}:#{name}") end %w(width height).each do |tag| full_name = "#{IMAGE_PREFIX}_#{tag}" disp_name = "#{IMAGE_PREFIX}:#{tag}" install_text_element(tag, IMAGE_URI, "?", full_name, :integer, disp_name) BaseListener.install_get_text_element(IMAGE_URI, tag, full_name) end alias width= image_width= alias width image_width alias height= image_height= alias height image_height def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] self.resource = args[1] end end def full_name tag_name_with_prefix(IMAGE_PREFIX) end private def maker_target(target) target.image_item end def setup_maker_attributes(item) item.about = self.about item.resource = self.resource end end end module ImageFaviconModel include ImageModelUtils extend BaseModel def self.append_features(klass) super unless klass.class == Module klass.install_have_child_element("favicon", IMAGE_URI, "?", "#{IMAGE_PREFIX}_favicon") klass.install_must_call_validator(IMAGE_PREFIX, IMAGE_URI) end end class ImageFavicon < Element include RSS10 include DublinCoreModel @tag_name = "favicon" class << self def required_prefix IMAGE_PREFIX end def required_uri IMAGE_URI end end [ ["about", ::RSS::RDF::URI, true, ::RSS::RDF::PREFIX], ["size", IMAGE_URI, true, IMAGE_PREFIX], ].each do |name, uri, required, prefix| install_get_attribute(name, uri, required, nil, nil, "#{prefix}:#{name}") end AVAILABLE_SIZES = %w(small medium large) alias_method :set_size, :size= private :set_size def size=(new_value) if @do_validate and !new_value.nil? new_value = new_value.strip unless AVAILABLE_SIZES.include?(new_value) attr_name = "#{IMAGE_PREFIX}:size" raise NotAvailableValueError.new(full_name, new_value, attr_name) end end set_size(new_value) end alias image_size= size= alias image_size size def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.about = args[0] self.size = args[1] end end def full_name tag_name_with_prefix(IMAGE_PREFIX) end private def maker_target(target) target.image_favicon end def setup_maker_attributes(favicon) favicon.about = self.about favicon.size = self.size end end end class RDF class Channel; include ImageFaviconModel; end class Item; include ImageItemModel; 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/rss/xmlscanner.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/xmlscanner.rb
require 'xmlscan/scanner' require 'stringio' module RSS class XMLScanParser < BaseParser class << self def listener XMLScanListener end end private def _parse begin if @rss.is_a?(String) input = StringIO.new(@rss) else input = @rss end scanner = XMLScan::XMLScanner.new(@listener) scanner.parse(input) rescue XMLScan::Error => e lineno = e.lineno || scanner.lineno || input.lineno raise NotWellFormedError.new(lineno){e.message} end end end class XMLScanListener < BaseListener include XMLScan::Visitor include ListenerMixin ENTITIES = { 'lt' => '<', 'gt' => '>', 'amp' => '&', 'quot' => '"', 'apos' => '\'' } def on_xmldecl_version(str) @version = str end def on_xmldecl_encoding(str) @encoding = str end def on_xmldecl_standalone(str) @standalone = str end def on_xmldecl_end xmldecl(@version, @encoding, @standalone == "yes") end alias_method(:on_pi, :instruction) alias_method(:on_chardata, :text) alias_method(:on_cdata, :text) def on_etag(name) tag_end(name) end def on_entityref(ref) text(entity(ref)) end def on_charref(code) text([code].pack('U')) end alias_method(:on_charref_hex, :on_charref) def on_stag(name) @attrs = {} end def on_attribute(name) @attrs[name] = @current_attr = '' end def on_attr_value(str) @current_attr << str end def on_attr_entityref(ref) @current_attr << entity(ref) end def on_attr_charref(code) @current_attr << [code].pack('U') end alias_method(:on_attr_charref_hex, :on_attr_charref) def on_stag_end(name) tag_start(name, @attrs) end def on_stag_end_empty(name) tag_start(name, @attrs) tag_end(name) end private def entity(ref) ent = ENTITIES[ref] if ent ent else wellformed_error("undefined entity: #{ref}") 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/rss/trackback.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/trackback.rb
require 'rss/1.0' require 'rss/2.0' module RSS TRACKBACK_PREFIX = 'trackback' TRACKBACK_URI = 'http://madskills.com/public/xml/rss/module/trackback/' RDF.install_ns(TRACKBACK_PREFIX, TRACKBACK_URI) Rss.install_ns(TRACKBACK_PREFIX, TRACKBACK_URI) module TrackBackUtils private def trackback_validate(ignore_unknown_element, tags, uri) return if tags.nil? if tags.find {|tag| tag == "about"} and !tags.find {|tag| tag == "ping"} raise MissingTagError.new("#{TRACKBACK_PREFIX}:ping", tag_name) end end end module BaseTrackBackModel ELEMENTS = %w(ping about) def append_features(klass) super unless klass.class == Module klass.module_eval {include TrackBackUtils} klass.install_must_call_validator(TRACKBACK_PREFIX, TRACKBACK_URI) %w(ping).each do |name| var_name = "#{TRACKBACK_PREFIX}_#{name}" klass_name = "TrackBack#{Utils.to_class_name(name)}" klass.install_have_child_element(name, TRACKBACK_URI, "?", var_name) klass.module_eval(<<-EOC, __FILE__, __LINE__) remove_method :#{var_name} def #{var_name} @#{var_name} and @#{var_name}.value end remove_method :#{var_name}= def #{var_name}=(value) @#{var_name} = Utils.new_with_value_if_need(#{klass_name}, value) end EOC end [%w(about s)].each do |name, postfix| var_name = "#{TRACKBACK_PREFIX}_#{name}" klass_name = "TrackBack#{Utils.to_class_name(name)}" klass.install_have_children_element(name, TRACKBACK_URI, "*", var_name) klass.module_eval(<<-EOC, __FILE__, __LINE__) remove_method :#{var_name} def #{var_name}(*args) if args.empty? @#{var_name}.first and @#{var_name}.first.value else ret = @#{var_name}.__send__("[]", *args) if ret.is_a?(Array) ret.collect {|x| x.value} else ret.value end end end remove_method :#{var_name}= remove_method :set_#{var_name} def #{var_name}=(*args) if args.size == 1 item = Utils.new_with_value_if_need(#{klass_name}, args[0]) @#{var_name}.push(item) else new_val = args.last if new_val.is_a?(Array) new_val = new_value.collect do |val| Utils.new_with_value_if_need(#{klass_name}, val) end else new_val = Utils.new_with_value_if_need(#{klass_name}, new_val) end @#{var_name}.__send__("[]=", *(args[0..-2] + [new_val])) end end alias set_#{var_name} #{var_name}= EOC end end end end module TrackBackModel10 extend BaseModel extend BaseTrackBackModel class TrackBackPing < Element include RSS10 class << self def required_prefix TRACKBACK_PREFIX end def required_uri TRACKBACK_URI end end @tag_name = "ping" [ ["resource", ::RSS::RDF::URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{::RSS::RDF::PREFIX}:#{name}") end alias_method(:value, :resource) alias_method(:value=, :resource=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end end class TrackBackAbout < Element include RSS10 class << self def required_prefix TRACKBACK_PREFIX end def required_uri TRACKBACK_URI end end @tag_name = "about" [ ["resource", ::RSS::RDF::URI, true] ].each do |name, uri, required| install_get_attribute(name, uri, required, nil, nil, "#{::RSS::RDF::PREFIX}:#{name}") end alias_method(:value, :resource) alias_method(:value=, :resource=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.resource = args[0] end end def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end private def maker_target(abouts) abouts.new_about end def setup_maker_attributes(about) about.resource = self.resource end end end module TrackBackModel20 extend BaseModel extend BaseTrackBackModel class TrackBackPing < Element include RSS09 @tag_name = "ping" content_setup class << self def required_prefix TRACKBACK_PREFIX end def required_uri TRACKBACK_URI end end alias_method(:value, :content) alias_method(:value=, :content=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end end class TrackBackAbout < Element include RSS09 @tag_name = "about" content_setup class << self def required_prefix TRACKBACK_PREFIX end def required_uri TRACKBACK_URI end end alias_method(:value, :content) alias_method(:value=, :content=) def initialize(*args) if Utils.element_initialize_arguments?(args) super else super() self.content = args[0] end end def full_name tag_name_with_prefix(TRACKBACK_PREFIX) end end end class RDF class Item; include TrackBackModel10; end end class Rss class Channel class Item; include TrackBackModel20; end end end BaseTrackBackModel::ELEMENTS.each do |name| class_name = Utils.to_class_name(name) BaseListener.install_class_name(TRACKBACK_URI, name, "TrackBack#{class_name}") end BaseTrackBackModel::ELEMENTS.collect! {|name| "#{TRACKBACK_PREFIX}_#{name}"} 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/rss/content/1.0.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/content/1.0.rb
require 'rss/1.0' require 'rss/content' module RSS RDF.install_ns(CONTENT_PREFIX, CONTENT_URI) class RDF class Item; include ContentModel; 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/rss/content/2.0.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/content/2.0.rb
require "rss/2.0" require "rss/content" module RSS Rss.install_ns(CONTENT_PREFIX, CONTENT_URI) class Rss class Channel class Item; include ContentModel; 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/rss/dublincore/1.0.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/dublincore/1.0.rb
require "rss/1.0" require "rss/dublincore" module RSS RDF.install_ns(DC_PREFIX, DC_URI) class RDF class Channel; include DublinCoreModel; end class Image; include DublinCoreModel; end class Item; include DublinCoreModel; end class Textinput; include DublinCoreModel; 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/rss/dublincore/2.0.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/dublincore/2.0.rb
require "rss/2.0" require "rss/dublincore" module RSS Rss.install_ns(DC_PREFIX, DC_URI) class Rss class Channel include DublinCoreModel class Item; include DublinCoreModel; 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/rss/dublincore/atom.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/dublincore/atom.rb
require "rss/atom" require "rss/dublincore" module RSS module Atom Feed.install_ns(DC_PREFIX, DC_URI) class Feed include DublinCoreModel class Entry; include DublinCoreModel; end end class Entry include DublinCoreModel 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/rss/maker/feed.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/feed.rb
require "rss/maker/atom" module RSS module Maker module Atom class Feed < RSSBase def initialize(feed_version="1.0") super @feed_type = "atom" @feed_subtype = "feed" end private def make_feed ::RSS::Atom::Feed.new(@version, @encoding, @standalone) end def setup_elements(feed) setup_channel(feed) setup_image(feed) setup_items(feed) end class Channel < ChannelBase def to_feed(feed) set_default_values do setup_values(feed) feed.dc_dates.clear setup_other_elements(feed) if image_favicon.about icon = feed.class::Icon.new icon.content = image_favicon.about feed.icon = icon end unless have_required_values? raise NotSetError.new("maker.channel", not_set_required_variables) end end end def have_required_values? super and (!authors.empty? or @maker.items.any? {|item| !item.authors.empty?}) end private def required_variable_names %w(id updated) end def variables super + %w(id updated) end def variable_is_set? super or !authors.empty? end def not_set_required_variables vars = super if authors.empty? and @maker.items.all? {|item| item.author.to_s.empty?} vars << "author" end vars << "title" unless title {|t| t.have_required_values?} vars end def _set_default_values(&block) keep = { :id => id, :updated => updated, } self.id ||= about self.updated ||= dc_date super(&block) ensure self.id = keep[:id] self.updated = keep[:updated] end class SkipDays < SkipDaysBase def to_feed(*args) end class Day < DayBase end end class SkipHours < SkipHoursBase def to_feed(*args) end class Hour < HourBase end end class Cloud < CloudBase def to_feed(*args) end end class Categories < CategoriesBase class Category < CategoryBase include AtomCategory def self.not_set_name "maker.channel.category" end end end class Links < LinksBase class Link < LinkBase include AtomLink def self.not_set_name "maker.channel.link" end end end AtomPersons.def_atom_persons(self, "author", "maker.channel.author") AtomPersons.def_atom_persons(self, "contributor", "maker.channel.contributor") class Generator < GeneratorBase include AtomGenerator def self.not_set_name "maker.channel.generator" end end AtomTextConstruct.def_atom_text_construct(self, "rights", "maker.channel.copyright", "Copyright") AtomTextConstruct.def_atom_text_construct(self, "subtitle", "maker.channel.description", "Description") AtomTextConstruct.def_atom_text_construct(self, "title", "maker.channel.title") end class Image < ImageBase def to_feed(feed) logo = feed.class::Logo.new class << logo alias_method(:url=, :content=) end set = setup_values(logo) class << logo remove_method(:url=) end if set feed.logo = logo set_parent(logo, feed) setup_other_elements(feed, logo) elsif variable_is_set? raise NotSetError.new("maker.image", not_set_required_variables) end end private def required_variable_names %w(url) end end class Items < ItemsBase def to_feed(feed) normalize.each do |item| item.to_feed(feed) end setup_other_elements(feed, feed.entries) end class Item < ItemBase def to_feed(feed) set_default_values do entry = feed.class::Entry.new set = setup_values(entry) setup_other_elements(feed, entry) if set feed.entries << entry set_parent(entry, feed) elsif variable_is_set? raise NotSetError.new("maker.item", not_set_required_variables) end end end def have_required_values? set_default_values do super and title {|t| t.have_required_values?} end end private def required_variable_names %w(id updated) end def variables super + ["updated"] end def not_set_required_variables vars = super vars << "title" unless title {|t| t.have_required_values?} vars end def _set_default_values(&block) keep = { :id => id, :updated => updated, } self.id ||= link self.updated ||= dc_date super(&block) ensure self.id = keep[:id] self.updated = keep[:updated] end class Guid < GuidBase def to_feed(feed, current) end end class Enclosure < EnclosureBase def to_feed(feed, current) end end class Source < SourceBase def to_feed(feed, current) source = current.class::Source.new setup_values(source) current.source = source set_parent(source, current) setup_other_elements(feed, source) current.source = nil if source.to_s == "<source/>" end private def required_variable_names [] end def variables super + ["updated"] end AtomPersons.def_atom_persons(self, "author", "maker.item.source.author") AtomPersons.def_atom_persons(self, "contributor", "maker.item.source.contributor") class Categories < CategoriesBase class Category < CategoryBase include AtomCategory def self.not_set_name "maker.item.source.category" end end end class Generator < GeneratorBase include AtomGenerator def self.not_set_name "maker.item.source.generator" end end class Icon < IconBase def to_feed(feed, current) icon = current.class::Icon.new class << icon alias_method(:url=, :content=) end set = setup_values(icon) class << icon remove_method(:url=) end if set current.icon = icon set_parent(icon, current) setup_other_elements(feed, icon) elsif variable_is_set? raise NotSetError.new("maker.item.source.icon", not_set_required_variables) end end private def required_variable_names %w(url) end end class Links < LinksBase class Link < LinkBase include AtomLink def self.not_set_name "maker.item.source.link" end end end class Logo < LogoBase include AtomLogo def self.not_set_name "maker.item.source.logo" end end maker_name_base = "maker.item.source." maker_name = "#{maker_name_base}rights" AtomTextConstruct.def_atom_text_construct(self, "rights", maker_name) maker_name = "#{maker_name_base}subtitle" AtomTextConstruct.def_atom_text_construct(self, "subtitle", maker_name) maker_name = "#{maker_name_base}title" AtomTextConstruct.def_atom_text_construct(self, "title", maker_name) end class Categories < CategoriesBase class Category < CategoryBase include AtomCategory def self.not_set_name "maker.item.category" end end end AtomPersons.def_atom_persons(self, "author", "maker.item.author") AtomPersons.def_atom_persons(self, "contributor", "maker.item.contributor") class Links < LinksBase class Link < LinkBase include AtomLink def self.not_set_name "maker.item.link" end end end AtomTextConstruct.def_atom_text_construct(self, "rights", "maker.item.rights") AtomTextConstruct.def_atom_text_construct(self, "summary", "maker.item.description", "Description") AtomTextConstruct.def_atom_text_construct(self, "title", "maker.item.title") class Content < ContentBase def to_feed(feed, current) content = current.class::Content.new if setup_values(content) content.src = nil if content.src and content.content current.content = content set_parent(content, current) setup_other_elements(feed, content) elsif variable_is_set? raise NotSetError.new("maker.item.content", not_set_required_variables) end end alias_method(:xml, :xml_content) private def required_variable_names if out_of_line? %w(type) elsif xml_type? %w(xml_content) else %w(content) end end def variables if out_of_line? super elsif xml_type? super + %w(xml) else super end end def xml_type? _type = type return false if _type.nil? _type == "xhtml" or /(?:\+xml|\/xml)$/i =~ _type or %w(text/xml-external-parsed-entity application/xml-external-parsed-entity application/xml-dtd).include?(_type.downcase) end end end end class Textinput < TextinputBase end end end add_maker("atom", "1.0", Atom::Feed) add_maker("atom:feed", "1.0", Atom::Feed) add_maker("atom1.0", "1.0", Atom::Feed) add_maker("atom1.0:feed", "1.0", Atom::Feed) 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/rss/maker/entry.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/entry.rb
require "rss/maker/atom" require "rss/maker/feed" module RSS module Maker module Atom class Entry < RSSBase def initialize(feed_version="1.0") super @feed_type = "atom" @feed_subtype = "entry" end private def make_feed ::RSS::Atom::Entry.new(@version, @encoding, @standalone) end def setup_elements(entry) setup_items(entry) end class Channel < ChannelBase class SkipDays < SkipDaysBase class Day < DayBase end end class SkipHours < SkipHoursBase class Hour < HourBase end end class Cloud < CloudBase end Categories = Feed::Channel::Categories Links = Feed::Channel::Links Authors = Feed::Channel::Authors Contributors = Feed::Channel::Contributors class Generator < GeneratorBase include AtomGenerator def self.not_set_name "maker.channel.generator" end end Copyright = Feed::Channel::Copyright class Description < DescriptionBase end Title = Feed::Channel::Title end class Image < ImageBase end class Items < ItemsBase def to_feed(entry) (normalize.first || Item.new(@maker)).to_feed(entry) end class Item < ItemBase def to_feed(entry) set_default_values do setup_values(entry) entry.dc_dates.clear setup_other_elements(entry) unless have_required_values? raise NotSetError.new("maker.item", not_set_required_variables) end end end private def required_variable_names %w(id updated) end def variables super + ["updated"] end def variable_is_set? super or !authors.empty? end def not_set_required_variables set_default_values do vars = super if authors.all? {|author| !author.have_required_values?} vars << "author" end vars << "title" unless title {|t| t.have_required_values?} vars end end def _set_default_values(&block) keep = { :authors => authors.to_a.dup, :contributors => contributors.to_a.dup, :categories => categories.to_a.dup, :id => id, :links => links.to_a.dup, :rights => @rights, :title => @title, :updated => updated, } authors.replace(@maker.channel.authors) if keep[:authors].empty? if keep[:contributors].empty? contributors.replace(@maker.channel.contributors) end if keep[:categories].empty? categories.replace(@maker.channel.categories) end self.id ||= link || @maker.channel.id links.replace(@maker.channel.links) if keep[:links].empty? unless keep[:rights].variable_is_set? @maker.channel.rights {|r| @rights = r} end unless keep[:title].variable_is_set? @maker.channel.title {|t| @title = t} end self.updated ||= @maker.channel.updated super(&block) ensure authors.replace(keep[:authors]) contributors.replace(keep[:contributors]) categories.replace(keep[:categories]) links.replace(keep[:links]) self.id = keep[:id] @rights = keep[:rights] @title = keep[:title] self.updated = keep[:prev_updated] end Guid = Feed::Items::Item::Guid Enclosure = Feed::Items::Item::Enclosure Source = Feed::Items::Item::Source Categories = Feed::Items::Item::Categories Authors = Feed::Items::Item::Authors Contributors = Feed::Items::Item::Contributors Links = Feed::Items::Item::Links Rights = Feed::Items::Item::Rights Description = Feed::Items::Item::Description Title = Feed::Items::Item::Title Content = Feed::Items::Item::Content end end class Textinput < TextinputBase end end end add_maker("atom:entry", "1.0", Atom::Entry) add_maker("atom1.0:entry", "1.0", Atom::Entry) 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/rss/maker/content.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/content.rb
require 'rss/content' require 'rss/maker/1.0' require 'rss/maker/2.0' module RSS module Maker module ContentModel def self.append_features(klass) super ::RSS::ContentModel::ELEMENTS.each do |name| klass.def_other_element(name) end end end class ItemsBase class ItemBase; include ContentModel; 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/rss/maker/syndication.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/syndication.rb
require 'rss/syndication' require 'rss/maker/1.0' module RSS module Maker module SyndicationModel def self.append_features(klass) super ::RSS::SyndicationModel::ELEMENTS.each do |name| klass.def_other_element(name) end end end class ChannelBase; include SyndicationModel; 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/rss/maker/taxonomy.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/taxonomy.rb
require 'rss/taxonomy' require 'rss/maker/1.0' require 'rss/maker/dublincore' module RSS module Maker module TaxonomyTopicsModel def self.append_features(klass) super klass.def_classed_element("#{RSS::TAXO_PREFIX}_topics", "TaxonomyTopics") end def self.install_taxo_topics(klass) klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class TaxonomyTopics < TaxonomyTopicsBase def to_feed(feed, current) if current.respond_to?(:taxo_topics) topics = current.class::TaxonomyTopics.new bag = topics.Bag @resources.each do |resource| bag.lis << RDF::Bag::Li.new(resource) end current.taxo_topics = topics end end end EOC end class TaxonomyTopicsBase < Base attr_reader :resources def_array_element("resource") remove_method :new_resource end end module TaxonomyTopicModel def self.append_features(klass) super class_name = "TaxonomyTopics" klass.def_classed_elements("#{TAXO_PREFIX}_topic", "value", class_name) end def self.install_taxo_topic(klass) klass.module_eval(<<-EOC, __FILE__, __LINE__ + 1) class TaxonomyTopics < TaxonomyTopicsBase class TaxonomyTopic < TaxonomyTopicBase DublinCoreModel.install_dublin_core(self) TaxonomyTopicsModel.install_taxo_topics(self) def to_feed(feed, current) if current.respond_to?(:taxo_topics) topic = current.class::TaxonomyTopic.new(value) topic.taxo_link = value taxo_topics.to_feed(feed, topic) if taxo_topics current.taxo_topics << topic setup_other_elements(feed, topic) end end end end EOC end class TaxonomyTopicsBase < Base def_array_element("topic", nil, "TaxonomyTopic") alias_method(:new_taxo_topic, :new_topic) # For backward compatibility class TaxonomyTopicBase < Base include DublinCoreModel include TaxonomyTopicsModel attr_accessor :value add_need_initialize_variable("value") alias_method(:taxo_link, :value) alias_method(:taxo_link=, :value=) def have_required_values? @value end end end end class RSSBase include TaxonomyTopicModel end class ChannelBase include TaxonomyTopicsModel end class ItemsBase class ItemBase include TaxonomyTopicsModel end end makers.each do |maker| maker.module_eval(<<-EOC, __FILE__, __LINE__ + 1) TaxonomyTopicModel.install_taxo_topic(self) class Channel TaxonomyTopicsModel.install_taxo_topics(self) end class Items class Item TaxonomyTopicsModel.install_taxo_topics(self) end end EOC 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/rss/maker/1.0.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/1.0.rb
require "rss/1.0" require "rss/maker/base" module RSS module Maker class RSS10 < RSSBase def initialize(feed_version="1.0") super @feed_type = "rss" end private def make_feed RDF.new(@version, @encoding, @standalone) end def setup_elements(rss) setup_channel(rss) setup_image(rss) setup_items(rss) setup_textinput(rss) end class Channel < ChannelBase def to_feed(rss) set_default_values do _not_set_required_variables = not_set_required_variables if _not_set_required_variables.empty? channel = RDF::Channel.new(@about) set = setup_values(channel) channel.dc_dates.clear rss.channel = channel set_parent(channel, rss) setup_items(rss) setup_image(rss) setup_textinput(rss) setup_other_elements(rss, channel) else raise NotSetError.new("maker.channel", _not_set_required_variables) end end end private def setup_items(rss) items = RDF::Channel::Items.new seq = items.Seq set_parent(items, seq) target_items = @maker.items.normalize raise NotSetError.new("maker", ["items"]) if target_items.empty? target_items.each do |item| li = RDF::Channel::Items::Seq::Li.new(item.link) seq.lis << li set_parent(li, seq) end rss.channel.items = items set_parent(rss.channel, items) end def setup_image(rss) if @maker.image.have_required_values? image = RDF::Channel::Image.new(@maker.image.url) rss.channel.image = image set_parent(image, rss.channel) end end def setup_textinput(rss) if @maker.textinput.have_required_values? textinput = RDF::Channel::Textinput.new(@maker.textinput.link) rss.channel.textinput = textinput set_parent(textinput, rss.channel) end end def required_variable_names %w(about link) end def not_set_required_variables vars = super vars << "description" unless description {|d| d.have_required_values?} vars << "title" unless title {|t| t.have_required_values?} vars end class SkipDays < SkipDaysBase def to_feed(*args) end class Day < DayBase end end class SkipHours < SkipHoursBase def to_feed(*args) end class Hour < HourBase end end class Cloud < CloudBase def to_feed(*args) end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Links < LinksBase def to_feed(rss, channel) return if @links.empty? @links.first.to_feed(rss, channel) end class Link < LinkBase def to_feed(rss, channel) if have_required_values? channel.link = href else raise NotSetError.new("maker.channel.link", not_set_required_variables) end end private def required_variable_names %w(href) end end end class Authors < AuthorsBase def to_feed(rss, channel) end class Author < AuthorBase def to_feed(rss, channel) end end end class Contributors < ContributorsBase def to_feed(rss, channel) end class Contributor < ContributorBase end end class Generator < GeneratorBase def to_feed(rss, channel) end end class Copyright < CopyrightBase def to_feed(rss, channel) end end class Description < DescriptionBase def to_feed(rss, channel) channel.description = content if have_required_values? end private def required_variable_names %w(content) end end class Title < TitleBase def to_feed(rss, channel) channel.title = content if have_required_values? end private def required_variable_names %w(content) end end end class Image < ImageBase def to_feed(rss) if @url image = RDF::Image.new(@url) set = setup_values(image) if set rss.image = image set_parent(image, rss) setup_other_elements(rss, image) end end end def have_required_values? super and @maker.channel.have_required_values? end private def variables super + ["link"] end def required_variable_names %w(url title link) end end class Items < ItemsBase def to_feed(rss) if rss.channel normalize.each do |item| item.to_feed(rss) end setup_other_elements(rss, rss.items) end end class Item < ItemBase def to_feed(rss) set_default_values do item = RDF::Item.new(link) set = setup_values(item) if set item.dc_dates.clear rss.items << item set_parent(item, rss) setup_other_elements(rss, item) elsif !have_required_values? raise NotSetError.new("maker.item", not_set_required_variables) end end end private def required_variable_names %w(link) end def variables super + %w(link) end def not_set_required_variables set_default_values do vars = super vars << "title" unless title {|t| t.have_required_values?} vars end end class Guid < GuidBase def to_feed(*args) end end class Enclosure < EnclosureBase def to_feed(*args) end end class Source < SourceBase def to_feed(*args) end class Authors < AuthorsBase def to_feed(*args) end class Author < AuthorBase end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Contributors < ContributorsBase def to_feed(*args) end class Contributor < ContributorBase end end class Generator < GeneratorBase def to_feed(*args) end end class Icon < IconBase def to_feed(*args) end end class Links < LinksBase def to_feed(*args) end class Link < LinkBase end end class Logo < LogoBase def to_feed(*args) end end class Rights < RightsBase def to_feed(*args) end end class Subtitle < SubtitleBase def to_feed(*args) end end class Title < TitleBase def to_feed(*args) end end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Authors < AuthorsBase def to_feed(*args) end class Author < AuthorBase end end class Links < LinksBase def to_feed(*args) end class Link < LinkBase end end class Contributors < ContributorsBase def to_feed(rss, item) end class Contributor < ContributorBase end end class Rights < RightsBase def to_feed(rss, item) end end class Description < DescriptionBase def to_feed(rss, item) item.description = content if have_required_values? end private def required_variable_names %w(content) end end class Content < ContentBase def to_feed(rss, item) end end class Title < TitleBase def to_feed(rss, item) item.title = content if have_required_values? end private def required_variable_names %w(content) end end end end class Textinput < TextinputBase def to_feed(rss) if @link textinput = RDF::Textinput.new(@link) set = setup_values(textinput) if set rss.textinput = textinput set_parent(textinput, rss) setup_other_elements(rss, textinput) end end end def have_required_values? super and @maker.channel.have_required_values? end private def required_variable_names %w(title description name link) end end end add_maker("1.0", "1.0", RSS10) add_maker("rss1.0", "1.0", RSS10) 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/rss/maker/2.0.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/2.0.rb
require "rss/2.0" require "rss/maker/0.9" module RSS module Maker class RSS20 < RSS09 def initialize(feed_version="2.0") super end class Channel < RSS09::Channel private def required_variable_names %w(link) end class SkipDays < RSS09::Channel::SkipDays class Day < RSS09::Channel::SkipDays::Day end end class SkipHours < RSS09::Channel::SkipHours class Hour < RSS09::Channel::SkipHours::Hour end end class Cloud < RSS09::Channel::Cloud def to_feed(rss, channel) cloud = Rss::Channel::Cloud.new set = setup_values(cloud) if set channel.cloud = cloud set_parent(cloud, channel) setup_other_elements(rss, cloud) end end private def required_variable_names %w(domain port path registerProcedure protocol) end end class Categories < RSS09::Channel::Categories def to_feed(rss, channel) @categories.each do |category| category.to_feed(rss, channel) end end class Category < RSS09::Channel::Categories::Category def to_feed(rss, channel) category = Rss::Channel::Category.new set = setup_values(category) if set channel.categories << category set_parent(category, channel) setup_other_elements(rss, category) end end private def required_variable_names %w(content) end end end class Generator < GeneratorBase def to_feed(rss, channel) channel.generator = content end private def required_variable_names %w(content) end end end class Image < RSS09::Image private def required_element? false end end class Items < RSS09::Items class Item < RSS09::Items::Item private def required_variable_names [] end def not_set_required_variables vars = super if !title {|t| t.have_required_values?} and !description {|d| d.have_required_values?} vars << "title or description" end vars end def variables super + ["pubDate"] end class Guid < RSS09::Items::Item::Guid def to_feed(rss, item) guid = Rss::Channel::Item::Guid.new set = setup_values(guid) if set item.guid = guid set_parent(guid, item) setup_other_elements(rss, guid) end end private def required_variable_names %w(content) end end class Enclosure < RSS09::Items::Item::Enclosure def to_feed(rss, item) enclosure = Rss::Channel::Item::Enclosure.new set = setup_values(enclosure) if set item.enclosure = enclosure set_parent(enclosure, item) setup_other_elements(rss, enclosure) end end private def required_variable_names %w(url length type) end end class Source < RSS09::Items::Item::Source def to_feed(rss, item) source = Rss::Channel::Item::Source.new set = setup_values(source) if set item.source = source set_parent(source, item) setup_other_elements(rss, source) end end private def required_variable_names %w(url content) end class Links < RSS09::Items::Item::Source::Links def to_feed(rss, source) return if @links.empty? @links.first.to_feed(rss, source) end class Link < RSS09::Items::Item::Source::Links::Link def to_feed(rss, source) source.url = href end end end end class Categories < RSS09::Items::Item::Categories def to_feed(rss, item) @categories.each do |category| category.to_feed(rss, item) end end class Category < RSS09::Items::Item::Categories::Category def to_feed(rss, item) category = Rss::Channel::Item::Category.new set = setup_values(category) if set item.categories << category set_parent(category, item) setup_other_elements(rss) end end private def required_variable_names %w(content) end end end class Authors < RSS09::Items::Item::Authors def to_feed(rss, item) return if @authors.empty? @authors.first.to_feed(rss, item) end class Author < RSS09::Items::Item::Authors::Author def to_feed(rss, item) item.author = name end end end end end class Textinput < RSS09::Textinput end end add_maker("2.0", "2.0", RSS20) add_maker("rss2.0", "2.0", RSS20) 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/rss/maker/base.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/base.rb
require 'forwardable' require 'rss/rss' module RSS module Maker class Base extend Utils::InheritedReader OTHER_ELEMENTS = [] NEED_INITIALIZE_VARIABLES = [] class << self def other_elements inherited_array_reader("OTHER_ELEMENTS") end def need_initialize_variables inherited_array_reader("NEED_INITIALIZE_VARIABLES") end def inherited_base ::RSS::Maker::Base end def inherited(subclass) subclass.const_set("OTHER_ELEMENTS", []) subclass.const_set("NEED_INITIALIZE_VARIABLES", []) end def add_other_element(variable_name) self::OTHER_ELEMENTS << variable_name end def add_need_initialize_variable(variable_name, init_value="nil") self::NEED_INITIALIZE_VARIABLES << [variable_name, init_value] end def def_array_element(name, plural=nil, klass_name=nil) include Enumerable extend Forwardable plural ||= "#{name}s" klass_name ||= Utils.to_class_name(name) def_delegators("@#{plural}", :<<, :[], :[]=, :first, :last) def_delegators("@#{plural}", :push, :pop, :shift, :unshift) def_delegators("@#{plural}", :each, :size, :empty?, :clear) add_need_initialize_variable(plural, "[]") module_eval(<<-EOC, __FILE__, __LINE__ + 1) def new_#{name} #{name} = self.class::#{klass_name}.new(@maker) @#{plural} << #{name} if block_given? yield #{name} else #{name} end end alias new_child new_#{name} def to_feed(*args) @#{plural}.each do |#{name}| #{name}.to_feed(*args) end end def replace(elements) @#{plural}.replace(elements.to_a) end EOC end def def_classed_element_without_accessor(name, class_name=nil) class_name ||= Utils.to_class_name(name) add_other_element(name) add_need_initialize_variable(name, "make_#{name}") module_eval(<<-EOC, __FILE__, __LINE__ + 1) private def setup_#{name}(feed, current) @#{name}.to_feed(feed, current) end def make_#{name} self.class::#{class_name}.new(@maker) end EOC end def def_classed_element(name, class_name=nil, attribute_name=nil) def_classed_element_without_accessor(name, class_name) if attribute_name module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name} if block_given? yield(@#{name}) else @#{name}.#{attribute_name} end end def #{name}=(new_value) @#{name}.#{attribute_name} = new_value end EOC else attr_reader name end end def def_classed_elements(name, attribute, plural_class_name=nil, plural_name=nil, new_name=nil) plural_name ||= "#{name}s" new_name ||= name def_classed_element(plural_name, plural_class_name) local_variable_name = "_#{name}" new_value_variable_name = "new_value" additional_setup_code = nil if block_given? additional_setup_code = yield(local_variable_name, new_value_variable_name) end module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name} #{local_variable_name} = #{plural_name}.first #{local_variable_name} ? #{local_variable_name}.#{attribute} : nil end def #{name}=(#{new_value_variable_name}) #{local_variable_name} = #{plural_name}.first || #{plural_name}.new_#{new_name} #{additional_setup_code} #{local_variable_name}.#{attribute} = #{new_value_variable_name} end EOC end def def_other_element(name) attr_accessor name def_other_element_without_accessor(name) end def def_other_element_without_accessor(name) add_need_initialize_variable(name) add_other_element(name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def setup_#{name}(feed, current) if !@#{name}.nil? and current.respond_to?(:#{name}=) current.#{name} = @#{name} end end EOC end def def_csv_element(name, type=nil) def_other_element_without_accessor(name) attr_reader(name) converter = "" if type == :integer converter = "{|v| Integer(v)}" end module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(value) @#{name} = Utils::CSV.parse(value)#{converter} end EOC end end attr_reader :maker def initialize(maker) @maker = maker @default_values_are_set = false initialize_variables end def have_required_values? not_set_required_variables.empty? end def variable_is_set? variables.any? {|var| not __send__(var).nil?} end private def initialize_variables self.class.need_initialize_variables.each do |variable_name, init_value| instance_eval("@#{variable_name} = #{init_value}", __FILE__, __LINE__) end end def setup_other_elements(feed, current=nil) current ||= current_element(feed) self.class.other_elements.each do |element| __send__("setup_#{element}", feed, current) end end def current_element(feed) feed end def set_default_values(&block) return yield if @default_values_are_set begin @default_values_are_set = true _set_default_values(&block) ensure @default_values_are_set = false end end def _set_default_values(&block) yield end def setup_values(target) set = false if have_required_values? variables.each do |var| setter = "#{var}=" if target.respond_to?(setter) value = __send__(var) if value target.__send__(setter, value) set = true end end end end set end def set_parent(target, parent) target.parent = parent if target.class.need_parent? end def variables self.class.need_initialize_variables.find_all do |name, init| "nil" == init end.collect do |name, init| name end end def not_set_required_variables required_variable_names.find_all do |var| __send__(var).nil? end end def required_variables_are_set? required_variable_names.each do |var| return false if __send__(var).nil? end true end end module AtomPersonConstructBase def self.append_features(klass) super klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1) %w(name uri email).each do |element| attr_accessor element add_need_initialize_variable(element) end EOC end end module AtomTextConstructBase module EnsureXMLContent class << self def included(base) super base.class_eval do %w(type content xml_content).each do |element| attr_reader element attr_writer element if element != "xml_content" add_need_initialize_variable(element) end alias_method(:xhtml, :xml_content) end end end def ensure_xml_content(content) xhtml_uri = ::RSS::Atom::XHTML_URI unless content.is_a?(RSS::XML::Element) and ["div", xhtml_uri] == [content.name, content.uri] children = content children = [children] unless content.is_a?(Array) children = set_xhtml_uri_as_default_uri(children) content = RSS::XML::Element.new("div", nil, xhtml_uri, {"xmlns" => xhtml_uri}, children) end content end def xml_content=(content) @xml_content = ensure_xml_content(content) end def xhtml=(content) self.xml_content = content end private def set_xhtml_uri_as_default_uri(children) children.collect do |child| if child.is_a?(RSS::XML::Element) and child.prefix.nil? and child.uri.nil? RSS::XML::Element.new(child.name, nil, ::RSS::Atom::XHTML_URI, child.attributes.dup, set_xhtml_uri_as_default_uri(child.children)) else child end end end end def self.append_features(klass) super klass.class_eval do include EnsureXMLContent end end end module SetupDefaultDate private def _set_default_values(&block) keep = { :date => date, :dc_dates => dc_dates.to_a.dup, } _date = date if _date and !dc_dates.any? {|dc_date| dc_date.value == _date} dc_date = self.class::DublinCoreDates::DublinCoreDate.new(self) dc_date.value = _date.dup dc_dates.unshift(dc_date) end self.date ||= self.dc_date super(&block) ensure date = keep[:date] dc_dates.replace(keep[:dc_dates]) end end class RSSBase < Base class << self def make(version, &block) new(version).make(&block) end end %w(xml_stylesheets channel image items textinput).each do |element| attr_reader element add_need_initialize_variable(element, "make_#{element}") module_eval(<<-EOC, __FILE__, __LINE__) private def setup_#{element}(feed) @#{element}.to_feed(feed) end def make_#{element} self.class::#{Utils.to_class_name(element)}.new(self) end EOC end attr_reader :feed_version alias_method(:rss_version, :feed_version) attr_accessor :version, :encoding, :standalone def initialize(feed_version) super(self) @feed_type = nil @feed_subtype = nil @feed_version = feed_version @version = "1.0" @encoding = "UTF-8" @standalone = nil end def make if block_given? yield(self) to_feed else nil end end def to_feed feed = make_feed setup_xml_stylesheets(feed) setup_elements(feed) setup_other_elements(feed) if feed.valid? feed else nil end end private remove_method :make_xml_stylesheets def make_xml_stylesheets XMLStyleSheets.new(self) end end class XMLStyleSheets < Base def_array_element("xml_stylesheet", nil, "XMLStyleSheet") class XMLStyleSheet < Base ::RSS::XMLStyleSheet::ATTRIBUTES.each do |attribute| attr_accessor attribute add_need_initialize_variable(attribute) end def to_feed(feed) xss = ::RSS::XMLStyleSheet.new guess_type_if_need(xss) set = setup_values(xss) if set feed.xml_stylesheets << xss end end private def guess_type_if_need(xss) if @type.nil? xss.href = @href @type = xss.type end end def required_variable_names %w(href type) end end end class ChannelBase < Base include SetupDefaultDate %w(cloud categories skipDays skipHours).each do |name| def_classed_element(name) end %w(generator copyright description title).each do |name| def_classed_element(name, nil, "content") end [ ["link", "href", Proc.new {|target,| "#{target}.href = 'self'"}], ["author", "name"], ["contributor", "name"], ].each do |name, attribute, additional_setup_maker| def_classed_elements(name, attribute, &additional_setup_maker) end %w(id about language managingEditor webMaster rating docs date lastBuildDate ttl).each do |element| attr_accessor element add_need_initialize_variable(element) end def pubDate date end def pubDate=(date) self.date = date end def updated date end def updated=(date) self.date = date end alias_method(:rights, :copyright) alias_method(:rights=, :copyright=) alias_method(:subtitle, :description) alias_method(:subtitle=, :description=) def icon image_favicon.about end def icon=(url) image_favicon.about = url end def logo maker.image.url end def logo=(url) maker.image.url = url end class SkipDaysBase < Base def_array_element("day") class DayBase < Base %w(content).each do |element| attr_accessor element add_need_initialize_variable(element) end end end class SkipHoursBase < Base def_array_element("hour") class HourBase < Base %w(content).each do |element| attr_accessor element add_need_initialize_variable(element) end end end class CloudBase < Base %w(domain port path registerProcedure protocol).each do |element| attr_accessor element add_need_initialize_variable(element) end end class CategoriesBase < Base def_array_element("category", "categories") class CategoryBase < Base %w(domain content label).each do |element| attr_accessor element add_need_initialize_variable(element) end alias_method(:term, :domain) alias_method(:term=, :domain=) alias_method(:scheme, :content) alias_method(:scheme=, :content=) end end class LinksBase < Base def_array_element("link") class LinkBase < Base %w(href rel type hreflang title length).each do |element| attr_accessor element add_need_initialize_variable(element) end end end class AuthorsBase < Base def_array_element("author") class AuthorBase < Base include AtomPersonConstructBase end end class ContributorsBase < Base def_array_element("contributor") class ContributorBase < Base include AtomPersonConstructBase end end class GeneratorBase < Base %w(uri version content).each do |element| attr_accessor element add_need_initialize_variable(element) end end class CopyrightBase < Base include AtomTextConstructBase end class DescriptionBase < Base include AtomTextConstructBase end class TitleBase < Base include AtomTextConstructBase end end class ImageBase < Base %w(title url width height description).each do |element| attr_accessor element add_need_initialize_variable(element) end def link @maker.channel.link end end class ItemsBase < Base def_array_element("item") attr_accessor :do_sort, :max_size def initialize(maker) super @do_sort = false @max_size = -1 end def normalize if @max_size >= 0 sort_if_need[0...@max_size] else sort_if_need[0..@max_size] end end private def sort_if_need if @do_sort.respond_to?(:call) @items.sort do |x, y| @do_sort.call(x, y) end elsif @do_sort @items.sort do |x, y| y <=> x end else @items end end class ItemBase < Base include SetupDefaultDate %w(guid enclosure source categories content).each do |name| def_classed_element(name) end %w(rights description title).each do |name| def_classed_element(name, nil, "content") end [ ["author", "name"], ["link", "href", Proc.new {|target,| "#{target}.href = 'alternate'"}], ["contributor", "name"], ].each do |name, attribute| def_classed_elements(name, attribute) end %w(date comments id published).each do |element| attr_accessor element add_need_initialize_variable(element) end def pubDate date end def pubDate=(date) self.date = date end def updated date end def updated=(date) self.date = date end alias_method(:summary, :description) alias_method(:summary=, :description=) def <=>(other) _date = date || dc_date _other_date = other.date || other.dc_date if _date and _other_date _date <=> _other_date elsif _date 1 elsif _other_date -1 else 0 end end class GuidBase < Base %w(isPermaLink content).each do |element| attr_accessor element add_need_initialize_variable(element) end end class EnclosureBase < Base %w(url length type).each do |element| attr_accessor element add_need_initialize_variable(element) end end class SourceBase < Base %w(authors categories contributors generator icon logo rights subtitle title).each do |name| def_classed_element(name) end [ ["link", "href"], ].each do |name, attribute| def_classed_elements(name, attribute) end %w(id content date).each do |element| attr_accessor element add_need_initialize_variable(element) end alias_method(:url, :link) alias_method(:url=, :link=) def updated date end def updated=(date) self.date = date end private AuthorsBase = ChannelBase::AuthorsBase CategoriesBase = ChannelBase::CategoriesBase ContributorsBase = ChannelBase::ContributorsBase GeneratorBase = ChannelBase::GeneratorBase class IconBase < Base %w(url).each do |element| attr_accessor element add_need_initialize_variable(element) end end LinksBase = ChannelBase::LinksBase class LogoBase < Base %w(uri).each do |element| attr_accessor element add_need_initialize_variable(element) end end class RightsBase < Base include AtomTextConstructBase end class SubtitleBase < Base include AtomTextConstructBase end class TitleBase < Base include AtomTextConstructBase end end CategoriesBase = ChannelBase::CategoriesBase AuthorsBase = ChannelBase::AuthorsBase LinksBase = ChannelBase::LinksBase ContributorsBase = ChannelBase::ContributorsBase class RightsBase < Base include AtomTextConstructBase end class DescriptionBase < Base include AtomTextConstructBase end class ContentBase < Base include AtomTextConstructBase::EnsureXMLContent %w(src).each do |element| attr_accessor(element) add_need_initialize_variable(element) end def xml_content=(content) content = ensure_xml_content(content) if inline_xhtml? @xml_content = content end alias_method(:xml, :xml_content) alias_method(:xml=, :xml_content=) def inline_text? [nil, "text", "html"].include?(@type) end def inline_html? @type == "html" end def inline_xhtml? @type == "xhtml" end def inline_other? !out_of_line? and ![nil, "text", "html", "xhtml"].include?(@type) end def inline_other_text? return false if @type.nil? or out_of_line? /\Atext\//i.match(@type) ? true : false end def inline_other_xml? return false if @type.nil? or out_of_line? /[\+\/]xml\z/i.match(@type) ? true : false end def inline_other_base64? return false if @type.nil? or out_of_line? @type.include?("/") and !inline_other_text? and !inline_other_xml? end def out_of_line? not @src.nil? and @content.nil? end end class TitleBase < Base include AtomTextConstructBase end end end class TextinputBase < Base %w(title description name link).each do |element| attr_accessor element add_need_initialize_variable(element) 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/rss/maker/0.9.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/0.9.rb
require "rss/0.9" require "rss/maker/base" module RSS module Maker class RSS09 < RSSBase def initialize(feed_version="0.92") super @feed_type = "rss" end private def make_feed Rss.new(@feed_version, @version, @encoding, @standalone) end def setup_elements(rss) setup_channel(rss) end class Channel < ChannelBase def to_feed(rss) channel = Rss::Channel.new set = setup_values(channel) _not_set_required_variables = not_set_required_variables if _not_set_required_variables.empty? rss.channel = channel set_parent(channel, rss) setup_items(rss) setup_image(rss) setup_textinput(rss) setup_other_elements(rss, channel) rss else raise NotSetError.new("maker.channel", _not_set_required_variables) end end private def setup_items(rss) @maker.items.to_feed(rss) end def setup_image(rss) @maker.image.to_feed(rss) end def setup_textinput(rss) @maker.textinput.to_feed(rss) end def variables super + ["pubDate"] end def required_variable_names %w(link language) end def not_set_required_variables vars = super vars << "description" unless description {|d| d.have_required_values?} vars << "title" unless title {|t| t.have_required_values?} vars end class SkipDays < SkipDaysBase def to_feed(rss, channel) unless @days.empty? skipDays = Rss::Channel::SkipDays.new channel.skipDays = skipDays set_parent(skipDays, channel) @days.each do |day| day.to_feed(rss, skipDays.days) end end end class Day < DayBase def to_feed(rss, days) day = Rss::Channel::SkipDays::Day.new set = setup_values(day) if set days << day set_parent(day, days) setup_other_elements(rss, day) end end private def required_variable_names %w(content) end end end class SkipHours < SkipHoursBase def to_feed(rss, channel) unless @hours.empty? skipHours = Rss::Channel::SkipHours.new channel.skipHours = skipHours set_parent(skipHours, channel) @hours.each do |hour| hour.to_feed(rss, skipHours.hours) end end end class Hour < HourBase def to_feed(rss, hours) hour = Rss::Channel::SkipHours::Hour.new set = setup_values(hour) if set hours << hour set_parent(hour, hours) setup_other_elements(rss, hour) end end private def required_variable_names %w(content) end end end class Cloud < CloudBase def to_feed(*args) end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Links < LinksBase def to_feed(rss, channel) return if @links.empty? @links.first.to_feed(rss, channel) end class Link < LinkBase def to_feed(rss, channel) if have_required_values? channel.link = href else raise NotSetError.new("maker.channel.link", not_set_required_variables) end end private def required_variable_names %w(href) end end end class Authors < AuthorsBase def to_feed(rss, channel) end class Author < AuthorBase def to_feed(rss, channel) end end end class Contributors < ContributorsBase def to_feed(rss, channel) end class Contributor < ContributorBase end end class Generator < GeneratorBase def to_feed(rss, channel) end end class Copyright < CopyrightBase def to_feed(rss, channel) channel.copyright = content if have_required_values? end private def required_variable_names %w(content) end end class Description < DescriptionBase def to_feed(rss, channel) channel.description = content if have_required_values? end private def required_variable_names %w(content) end end class Title < TitleBase def to_feed(rss, channel) channel.title = content if have_required_values? end private def required_variable_names %w(content) end end end class Image < ImageBase def to_feed(rss) image = Rss::Channel::Image.new set = setup_values(image) if set image.link = link rss.channel.image = image set_parent(image, rss.channel) setup_other_elements(rss, image) elsif required_element? raise NotSetError.new("maker.image", not_set_required_variables) end end private def required_variable_names %w(url title link) end def required_element? true end end class Items < ItemsBase def to_feed(rss) if rss.channel normalize.each do |item| item.to_feed(rss) end setup_other_elements(rss, rss.items) end end class Item < ItemBase def to_feed(rss) item = Rss::Channel::Item.new set = setup_values(item) _not_set_required_variables = not_set_required_variables if _not_set_required_variables.empty? rss.items << item set_parent(item, rss.channel) setup_other_elements(rss, item) elsif variable_is_set? raise NotSetError.new("maker.items", _not_set_required_variables) end end private def required_variable_names [] end def not_set_required_variables vars = super if @maker.feed_version == "0.91" vars << "title" unless title {|t| t.have_required_values?} vars << "link" unless link {|l| l.have_required_values?} end vars end class Guid < GuidBase def to_feed(*args) end end class Enclosure < EnclosureBase def to_feed(*args) end end class Source < SourceBase def to_feed(*args) end class Authors < AuthorsBase def to_feed(*args) end class Author < AuthorBase end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Contributors < ContributorsBase def to_feed(*args) end class Contributor < ContributorBase end end class Generator < GeneratorBase def to_feed(*args) end end class Icon < IconBase def to_feed(*args) end end class Links < LinksBase def to_feed(*args) end class Link < LinkBase end end class Logo < LogoBase def to_feed(*args) end end class Rights < RightsBase def to_feed(*args) end end class Subtitle < SubtitleBase def to_feed(*args) end end class Title < TitleBase def to_feed(*args) end end end class Categories < CategoriesBase def to_feed(*args) end class Category < CategoryBase end end class Authors < AuthorsBase def to_feed(*args) end class Author < AuthorBase end end class Links < LinksBase def to_feed(rss, item) return if @links.empty? @links.first.to_feed(rss, item) end class Link < LinkBase def to_feed(rss, item) if have_required_values? item.link = href else raise NotSetError.new("maker.link", not_set_required_variables) end end private def required_variable_names %w(href) end end end class Contributors < ContributorsBase def to_feed(rss, item) end class Contributor < ContributorBase end end class Rights < RightsBase def to_feed(rss, item) end end class Description < DescriptionBase def to_feed(rss, item) item.description = content if have_required_values? end private def required_variable_names %w(content) end end class Content < ContentBase def to_feed(rss, item) end end class Title < TitleBase def to_feed(rss, item) item.title = content if have_required_values? end private def required_variable_names %w(content) end end end end class Textinput < TextinputBase def to_feed(rss) textInput = Rss::Channel::TextInput.new set = setup_values(textInput) if set rss.channel.textInput = textInput set_parent(textInput, rss.channel) setup_other_elements(rss, textInput) end end private def required_variable_names %w(title description name link) end end end add_maker("0.9", "0.92", RSS09) add_maker("0.91", "0.91", RSS09) add_maker("0.92", "0.92", RSS09) add_maker("rss0.91", "0.91", RSS09) add_maker("rss0.92", "0.92", RSS09) 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/rss/maker/atom.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/atom.rb
require "rss/atom" require "rss/maker/base" module RSS module Maker module AtomPersons module_function def def_atom_persons(klass, name, maker_name, plural=nil) plural ||= "#{name}s" klass_name = Utils.to_class_name(name) plural_klass_name = Utils.to_class_name(plural) klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1) class #{plural_klass_name} < #{plural_klass_name}Base class #{klass_name} < #{klass_name}Base def to_feed(feed, current) #{name} = feed.class::#{klass_name}.new set = setup_values(#{name}) unless set raise NotSetError.new(#{maker_name.dump}, not_set_required_variables) end current.#{plural} << #{name} set_parent(#{name}, current) setup_other_elements(#{name}) end private def required_variable_names %w(name) end end end EOC end end module AtomTextConstruct class << self def def_atom_text_construct(klass, name, maker_name, klass_name=nil, atom_klass_name=nil) klass_name ||= Utils.to_class_name(name) atom_klass_name ||= Utils.to_class_name(name) klass.class_eval(<<-EOC, __FILE__, __LINE__ + 1) class #{klass_name} < #{klass_name}Base include #{self.name} def to_feed(feed, current) #{name} = current.class::#{atom_klass_name}.new if setup_values(#{name}) current.#{name} = #{name} set_parent(#{name}, current) setup_other_elements(feed) elsif variable_is_set? raise NotSetError.new(#{maker_name.dump}, not_set_required_variables) end end end EOC end end private def required_variable_names if type == "xhtml" %w(xml_content) else %w(content) end end def variables if type == "xhtml" super + %w(xhtml) else super end end end module AtomCategory def to_feed(feed, current) category = feed.class::Category.new set = setup_values(category) if set current.categories << category set_parent(category, current) setup_other_elements(feed) else raise NotSetError.new(self.class.not_set_name, not_set_required_variables) end end private def required_variable_names %w(term) end def variables super + ["term", "scheme"] end end module AtomLink def to_feed(feed, current) link = feed.class::Link.new set = setup_values(link) if set current.links << link set_parent(link, current) setup_other_elements(feed) else raise NotSetError.new(self.class.not_set_name, not_set_required_variables) end end private def required_variable_names %w(href) end end module AtomGenerator def to_feed(feed, current) generator = current.class::Generator.new if setup_values(generator) current.generator = generator set_parent(generator, current) setup_other_elements(feed) elsif variable_is_set? raise NotSetError.new(self.class.not_set_name, not_set_required_variables) end end private def required_variable_names %w(content) end end module AtomLogo def to_feed(feed, current) logo = current.class::Logo.new class << logo alias_method(:uri=, :content=) end set = setup_values(logo) class << logo remove_method(:uri=) end if set current.logo = logo set_parent(logo, current) setup_other_elements(feed) elsif variable_is_set? raise NotSetError.new(self.class.not_set_name, not_set_required_variables) end end private def required_variable_names %w(uri) 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/rss/maker/slash.rb
tools/jruby-1.5.1/lib/ruby/1.8/rss/maker/slash.rb
require 'rss/slash' require 'rss/maker/1.0' module RSS module Maker module SlashModel def self.append_features(klass) super ::RSS::SlashModel::ELEMENT_INFOS.each do |name, type| full_name = "#{RSS::SLASH_PREFIX}_#{name}" case type when :csv_integer klass.def_csv_element(full_name, :integer) else klass.def_other_element(full_name) end end klass.module_eval do alias_method(:slash_hit_parades, :slash_hit_parade) alias_method(:slash_hit_parades=, :slash_hit_parade=) end end end class ItemsBase class ItemBase include SlashModel end end end end
ruby
MIT
d54702f194edd05389968cf8947465860abccc5d
2026-01-04T17:46:04.645080Z
false