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/gems/1.8/gems/Saikuro-1.1.0/lib/saikuro.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/Saikuro-1.1.0/lib/saikuro.rb | # $Id: saikuro.rb 39 2008-06-21 05:35:07Z zev $
# Saikruo uses the BSD license.
#
# Copyright (c) 2005, Ubiquitous Business Technology (http://ubit.com)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# * Neither the name of Ubiquitous Business Technology nor the names
# of its contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# == Author
# Zev Blut (zb@ubit.com)
require 'irb/ruby-lex'
require 'yaml'
# States to watch for
# once in def get the token after space, because it may also
# be something like + or << for operator overloading.
# Counts the number of tokens in each line.
class TokenCounter
include RubyToken
attr_reader :current_file
def initialize
@files = Hash.new
@tokens_per_line = Hash.new(0)
@current_file = ""
end
# Mark file to associate with the token count.
def set_current_file(file)
@current_file = file
@tokens_per_line = Hash.new(0)
@files[@current_file] = @tokens_per_line
end
# Iterate through all tracked files, passing the
# the provided formater the token counts.
def list_tokens_per_line(formater)
formater.start_count(@files.size)
@files.each do |fname, tok_per_line|
formater.start_file(fname)
tok_per_line.sort.each do |line,num|
formater.line_token_count(line,num)
end
formater.end_file
end
end
# Count the token for the passed line.
def count_token(line_no,token)
case token
when TkSPACE, TkNL, TkRD_COMMENT
# Do not count these as tokens
when TkCOMMENT
# Ignore this only for comments in a statement?
# Ignore TkCOLON,TkCOLON2 and operators? like "." etc..
when TkRBRACK, TkRPAREN, TkRBRACE
# Ignore the closing of an array/index/hash/paren
# The opening is counted, but no more.
# Thus [], () {} is counted as 1 token not 2.
else
# may want to filter out comments...
@tokens_per_line[line_no] += 1
end
end
end
# Main class and structure used to compute the
# cyclomatic complexity of Ruby programs.
class ParseState
include RubyToken
attr_accessor :name, :children, :complexity, :parent, :lines
@@top_state = nil
def ParseState.make_top_state()
@@top_state = ParseState.new(nil)
@@top_state.name = "__top__"
@@top_state
end
@@token_counter = TokenCounter.new
def ParseState.set_token_counter(counter)
@@token_counter = counter
end
def ParseState.get_token_counter
@@token_counter
end
def initialize(lexer,parent=nil)
@name = ""
@children = Array.new
@complexity = 0
@parent = parent
@lexer = lexer
@run = true
# To catch one line def statements, We always have one line.
@lines = 0
@last_token_line_and_char = Array.new
end
def top_state?
self == @@top_state
end
def lexer=(lexer)
@run = true
@lexer = lexer
end
def make_state(type,parent = nil)
cstate = type.new(@lexer,self)
parent.children<< cstate
cstate
end
def calc_complexity
complexity = @complexity
children.each do |child|
complexity += child.calc_complexity
end
complexity
end
def calc_lines
lines = @lines
children.each do |child|
lines += child.calc_lines
end
lines
end
def compute_state(formater)
if top_state?
compute_state_for_global(formater)
end
@children.each do |s|
s.compute_state(formater)
end
end
def compute_state_for_global(formater)
global_def, @children = @children.partition do |s|
!s.kind_of?(ParseClass)
end
return if global_def.empty?
gx = global_def.inject(0) { |c,s| s.calc_complexity }
gl = global_def.inject(0) { |c,s| s.calc_lines }
formater.start_class_compute_state("Global", "", gx, gl)
global_def.each do |s|
s.compute_state(formater)
end
formater.end_class_compute_state("")
end
# Count the tokens parsed if true else ignore them.
def count_tokens?
true
end
def parse
while @run do
tok = @lexer.token
@run = false if tok.nil?
if lexer_loop?(tok)
STDERR.puts "Lexer loop at line : #{@lexer.line_no} char #{@lexer.char_no}."
@run = false
end
@last_token_line_and_char<< [@lexer.line_no.to_i, @lexer.char_no.to_i, tok]
if $VERBOSE
puts "DEBUG: #{@lexer.line_no} #{tok.class}:#{tok.name if tok.respond_to?(:name)}"
end
@@token_counter.count_token(@lexer.line_no, tok) if count_tokens?
parse_token(tok)
end
end
# Ruby-Lexer can go into a loop if the file does not end with a newline.
def lexer_loop?(token)
return false if @last_token_line_and_char.empty?
loop_flag = false
last = @last_token_line_and_char.last
line = last[0]
char = last[1]
ltok = last[2]
if ( (line == @lexer.line_no.to_i) &&
(char == @lexer.char_no.to_i) &&
(ltok.class == token.class) )
# We are potentially in a loop
if @last_token_line_and_char.size >= 3
loop_flag = true
end
else
# Not in a loop so clear stack
@last_token_line_and_char = Array.new
end
loop_flag
end
def do_begin_token(token)
make_state(EndableParseState, self)
end
def do_class_token(token)
make_state(ParseClass,self)
end
def do_module_token(token)
make_state(ParseModule,self)
end
def do_def_token(token)
make_state(ParseDef,self)
end
def do_constant_token(token)
nil
end
def do_identifier_token(token)
if (token.name == "__END__" && token.char_no.to_i == 0)
# The Ruby code has stopped and the rest is data so cease parsing.
@run = false
end
nil
end
def do_right_brace_token(token)
nil
end
def do_end_token(token)
end_debug
nil
end
def do_block_token(token)
make_state(ParseBlock,self)
end
def do_conditional_token(token)
make_state(ParseCond,self)
end
def do_conditional_do_control_token(token)
make_state(ParseDoCond,self)
end
def do_case_token(token)
make_state(EndableParseState, self)
end
def do_one_line_conditional_token(token)
# This is an if with no end
@complexity += 1
#STDOUT.puts "got IF_MOD: #{self.to_yaml}" if $VERBOSE
#if state.type != "class" && state.type != "def" && state.type != "cond"
#STDOUT.puts "Changing IF_MOD Parent" if $VERBOSE
#state = state.parent
#@run = false
nil
end
def do_else_token(token)
STDOUT.puts "Ignored/Unknown Token:#{token.class}" if $VERBOSE
nil
end
def do_comment_token(token)
make_state(ParseComment, self)
end
def do_symbol_token(token)
make_state(ParseSymbol, self)
end
def parse_token(token)
state = nil
case token
when TkCLASS
state = do_class_token(token)
when TkMODULE
state = do_module_token(token)
when TkDEF
state = do_def_token(token)
when TkCONSTANT
# Nothing to do with a constant at top level?
state = do_constant_token(token)
when TkIDENTIFIER,TkFID
# Nothing to do at top level?
state = do_identifier_token(token)
when TkRBRACE
# Nothing to do at top level
state = do_right_brace_token(token)
when TkEND
state = do_end_token(token)
# At top level this might be an error...
when TkDO,TkfLBRACE
state = do_block_token(token)
when TkIF,TkUNLESS
state = do_conditional_token(token)
when TkWHILE,TkUNTIL,TkFOR
state = do_conditional_do_control_token(token)
when TkELSIF #,TkELSE
@complexity += 1
when TkELSE
# Else does not increase complexity
when TkCASE
state = do_case_token(token)
when TkWHEN
@complexity += 1
when TkBEGIN
state = do_begin_token(token)
when TkRESCUE
# Maybe this should add complexity and not begin
@complexity += 1
when TkIF_MOD, TkUNLESS_MOD, TkUNTIL_MOD, TkWHILE_MOD, TkQUESTION
state = do_one_line_conditional_token(token)
when TkNL
#
@lines += 1
when TkRETURN
# Early returns do not increase complexity as the condition that
# calls the return is the one that increases it.
when TkCOMMENT
state = do_comment_token(token)
when TkSYMBEG
state = do_symbol_token(token)
when TkError
STDOUT.puts "Lexer received an error for line #{@lexer.line_no} char #{@lexer.char_no}"
else
state = do_else_token(token)
end
state.parse if state
end
def end_debug
STDOUT.puts "got an end: #{@name} in #{self.class.name}" if $VERBOSE
if @parent.nil?
STDOUT.puts "DEBUG: Line #{@lexer.line_no}"
STDOUT.puts "DEBUG: #{@name}; #{self.class}"
# to_yaml can cause an infinite loop?
#STDOUT.puts "TOP: #{@@top_state.to_yaml}"
#STDOUT.puts "TOP: #{@@top_state.inspect}"
# This may not be an error?
#exit 1
end
end
end
# Read and consume tokens in comments until a new line.
class ParseComment < ParseState
# While in a comment state do not count the tokens.
def count_tokens?
false
end
def parse_token(token)
if token.is_a?(TkNL)
@lines += 1
@run = false
end
end
end
class ParseSymbol < ParseState
def initialize(lexer, parent = nil)
super
STDOUT.puts "STARTING SYMBOL" if $VERBOSE
end
def parse_token(token)
STDOUT.puts "Symbol's token is #{token.class}" if $VERBOSE
# Consume the next token and stop
@run = false
nil
end
end
class EndableParseState < ParseState
def initialize(lexer,parent=nil)
super(lexer,parent)
STDOUT.puts "Starting #{self.class}" if $VERBOSE
end
def do_end_token(token)
end_debug
@run = false
nil
end
end
class ParseClass < EndableParseState
def initialize(lexer,parent=nil)
super(lexer,parent)
@type_name = "Class"
end
def do_constant_token(token)
@name = token.name if @name.empty?
nil
end
def compute_state(formater)
# Seperate the Module and Class Children out
cnm_children, @children = @children.partition do |child|
child.kind_of?(ParseClass)
end
formater.start_class_compute_state(@type_name,@name,self.calc_complexity,self.calc_lines)
super(formater)
formater.end_class_compute_state(@name)
cnm_children.each do |child|
child.name = @name + "::" + child.name
child.compute_state(formater)
end
end
end
class ParseModule < ParseClass
def initialize(lexer,parent=nil)
super(lexer,parent)
@type_name = "Module"
end
end
class ParseDef < EndableParseState
def initialize(lexer,parent=nil)
super(lexer,parent)
@complexity = 1
@looking_for_name = true
@first_space = true
end
# This way I don't need to list all possible overload
# tokens.
def create_def_name(token)
case token
when TkSPACE
# mark first space so we can stop at next space
if @first_space
@first_space = false
else
@looking_for_name = false
end
when TkNL,TkLPAREN,TkfLPAREN,TkSEMICOLON
# we can also stop at a new line or left parenthesis
@looking_for_name = false
when TkDOT
@name<< "."
when TkCOLON2
@name<< "::"
when TkASSIGN
@name<< "="
when TkfLBRACK
@name<< "["
when TkRBRACK
@name<< "]"
else
begin
@name<< token.name.to_s
rescue Exception => err
#what is this?
STDOUT.puts @@token_counter.current_file
STDOUT.puts @name
STDOUT.puts token.inspect
STDOUT.puts err.message
exit 1
end
end
end
def parse_token(token)
if @looking_for_name
create_def_name(token)
end
super(token)
end
def compute_state(formater)
formater.def_compute_state(@name, self.calc_complexity, self.calc_lines)
super(formater)
end
end
class ParseCond < EndableParseState
def initialize(lexer,parent=nil)
super(lexer,parent)
@complexity = 1
end
end
class ParseDoCond < ParseCond
def initialize(lexer,parent=nil)
super(lexer,parent)
@looking_for_new_line = true
end
# Need to consume the do that can appear at the
# end of these control structures.
def parse_token(token)
if @looking_for_new_line
if token.is_a?(TkDO)
nil
else
if token.is_a?(TkNL)
@looking_for_new_line = false
end
super(token)
end
else
super(token)
end
end
end
class ParseBlock < EndableParseState
def initialize(lexer,parent=nil)
super(lexer,parent)
@complexity = 1
@lbraces = Array.new
end
# Because the token for a block and hash right brace is the same,
# we need to track the hash left braces to determine when an end is
# encountered.
def parse_token(token)
if token.is_a?(TkLBRACE)
@lbraces.push(true)
elsif token.is_a?(TkRBRACE)
if @lbraces.empty?
do_right_brace_token(token)
#do_end_token(token)
else
@lbraces.pop
end
else
super(token)
end
end
def do_right_brace_token(token)
# we are done ? what about a hash in a block :-/
@run = false
nil
end
end
# ------------ END Analyzer logic ------------------------------------
class Filter
attr_accessor :limit, :error, :warn
def initialize(limit = -1, error = 11, warn = 8)
@limit = limit
@error = error
@warn = warn
end
def ignore?(count)
count < @limit
end
def warn?(count)
count >= @warn
end
def error?(count)
count >= @error
end
end
class BaseFormater
attr_accessor :warnings, :errors, :current
def initialize(out, filter = nil)
@out = out
@filter = filter
reset_data
end
def warn_error?(num, marker)
klass = ""
if @filter.error?(num)
klass = ' class="error"'
@errors<< [@current, marker, num]
elsif @filter.warn?(num)
klass = ' class="warning"'
@warnings<< [@current, marker, num]
end
klass
end
def reset_data
@warnings = Array.new
@errors = Array.new
@current = ""
end
end
class TokenCounterFormater < BaseFormater
def start(new_out=nil)
reset_data
@out = new_out if new_out
@out.puts "Token Count"
end
def start_count(number_of_files)
@out.puts "Counting tokens for #{number_of_files} files."
end
def start_file(file_name)
@current = file_name
@out.puts "File:#{file_name}"
end
def line_token_count(line_number,number_of_tokens)
return if @filter.ignore?(number_of_tokens)
warn_error?(number_of_tokens, line_number)
@out.puts "Line:#{line_number} ; Tokens : #{number_of_tokens}"
end
def end_file
@out.puts ""
end
def end_count
end
def end
end
end
module HTMLStyleSheet
def HTMLStyleSheet.style_sheet
out = StringIO.new
out.puts "<style>"
out.puts 'body {'
out.puts ' margin: 20px;'
out.puts ' padding: 0;'
out.puts ' font-size: 12px;'
out.puts ' font-family: bitstream vera sans, verdana, arial, sans serif;'
out.puts ' background-color: #efefef;'
out.puts '}'
out.puts ''
out.puts 'table { '
out.puts ' border-collapse: collapse;'
out.puts ' /*border-spacing: 0;*/'
out.puts ' border: 1px solid #666;'
out.puts ' background-color: #fff;'
out.puts ' margin-bottom: 20px;'
out.puts '}'
out.puts ''
out.puts 'table, th, th+th, td, td+td {'
out.puts ' border: 1px solid #ccc;'
out.puts '}'
out.puts ''
out.puts 'table th {'
out.puts ' font-size: 12px;'
out.puts ' color: #fc0;'
out.puts ' padding: 4px 0;'
out.puts ' background-color: #336;'
out.puts '}'
out.puts ''
out.puts 'th, td {'
out.puts ' padding: 4px 10px;'
out.puts '}'
out.puts ''
out.puts 'td { '
out.puts ' font-size: 13px;'
out.puts '}'
out.puts ''
out.puts '.class_name {'
out.puts ' font-size: 17px;'
out.puts ' margin: 20px 0 0;'
out.puts '}'
out.puts ''
out.puts '.class_complexity {'
out.puts 'margin: 0 auto;'
out.puts '}'
out.puts ''
out.puts '.class_complexity>.class_complexity {'
out.puts ' margin: 0;'
out.puts '}'
out.puts ''
out.puts '.class_total_complexity, .class_total_lines, .start_token_count, .file_count {'
out.puts ' font-size: 13px;'
out.puts ' font-weight: bold;'
out.puts '}'
out.puts ''
out.puts '.class_total_complexity, .class_total_lines {'
out.puts ' color: #c00;'
out.puts '}'
out.puts ''
out.puts '.start_token_count, .file_count {'
out.puts ' color: #333;'
out.puts '}'
out.puts ''
out.puts '.warning {'
out.puts ' background-color: yellow;'
out.puts '}'
out.puts ''
out.puts '.error {'
out.puts ' background-color: #f00;'
out.puts '}'
out.puts "</style>"
out.string
end
def style_sheet
HTMLStyleSheet.style_sheet
end
end
class HTMLTokenCounterFormater < TokenCounterFormater
include HTMLStyleSheet
def start(new_out=nil)
reset_data
@out = new_out if new_out
@out.puts "<html>"
@out.puts style_sheet
@out.puts "<body>"
end
def start_count(number_of_files)
@out.puts "<div class=\"start_token_count\">"
@out.puts "Number of files: #{number_of_files}"
@out.puts "</div>"
end
def start_file(file_name)
@current = file_name
@out.puts "<div class=\"file_count\">"
@out.puts "<p class=\"file_name\">"
@out.puts "File: #{file_name}"
@out.puts "</p>"
@out.puts "<table width=\"100%\" border=\"1\">"
@out.puts "<tr><th>Line</th><th>Tokens</th></tr>"
end
def line_token_count(line_number,number_of_tokens)
return if @filter.ignore?(number_of_tokens)
klass = warn_error?(number_of_tokens, line_number)
@out.puts "<tr><td>#{line_number}</td><td#{klass}>#{number_of_tokens}</td></tr>"
end
def end_file
@out.puts "</table>"
end
def end_count
end
def end
@out.puts "</body>"
@out.puts "</html>"
end
end
class ParseStateFormater < BaseFormater
def start(new_out=nil)
reset_data
@out = new_out if new_out
end
def end
end
def start_class_compute_state(type_name,name,complexity,lines)
@current = name
@out.puts "-- START #{name} --"
@out.puts "Type:#{type_name} Name:#{name} Complexity:#{complexity} Lines:#{lines}"
end
def end_class_compute_state(name)
@out.puts "-- END #{name} --"
end
def def_compute_state(name,complexity,lines)
return if @filter.ignore?(complexity)
warn_error?(complexity, name)
@out.puts "Type:Def Name:#{name} Complexity:#{complexity} Lines:#{lines}"
end
end
class StateHTMLComplexityFormater < ParseStateFormater
include HTMLStyleSheet
def start(new_out=nil)
reset_data
@out = new_out if new_out
@out.puts "<html><head><title>Cyclometric Complexity</title></head>"
@out.puts style_sheet
@out.puts "<body>"
end
def end
@out.puts "</body>"
@out.puts "</html>"
end
def start_class_compute_state(type_name,name,complexity,lines)
@current = name
@out.puts "<div class=\"class_complexity\">"
@out.puts "<h2 class=\"class_name\">#{type_name} : #{name}</h2>"
@out.puts "<div class=\"class_total_complexity\">Total Complexity: #{complexity}</div>"
@out.puts "<div class=\"class_total_lines\">Total Lines: #{lines}</div>"
@out.puts "<table width=\"100%\" border=\"1\">"
@out.puts "<tr><th>Method</th><th>Complexity</th><th># Lines</th></tr>"
end
def end_class_compute_state(name)
@out.puts "</table>"
@out.puts "</div>"
end
def def_compute_state(name, complexity, lines)
return if @filter.ignore?(complexity)
klass = warn_error?(complexity, name)
@out.puts "<tr><td>#{name}</td><td#{klass}>#{complexity}</td><td>#{lines}</td></tr>"
end
end
module ResultIndexGenerator
def summarize_errors_and_warnings(enw, header)
return "" if enw.empty?
f = StringIO.new
erval = Hash.new { |h,k| h[k] = Array.new }
wval = Hash.new { |h,k| h[k] = Array.new }
enw.each do |fname, warnings, errors|
errors.each do |c,m,v|
erval[v] << [fname, c, m]
end
warnings.each do |c,m,v|
wval[v] << [fname, c, m]
end
end
f.puts "<h2 class=\"class_name\">Errors and Warnings</h2>"
f.puts "<table width=\"100%\" border=\"1\">"
f.puts header
f.puts print_summary_table_rows(erval, "error")
f.puts print_summary_table_rows(wval, "warning")
f.puts "</table>"
f.string
end
def print_summary_table_rows(ewvals, klass_type)
f = StringIO.new
ewvals.sort { |a,b| b <=> a}.each do |v, vals|
vals.sort.each do |fname, c, m|
f.puts "<tr><td><a href=\"./#{fname}\">#{c}</a></td><td>#{m}</td>"
f.puts "<td class=\"#{klass_type}\">#{v}</td></tr>"
end
end
f.string
end
def list_analyzed_files(files)
f = StringIO.new
f.puts "<h2 class=\"class_name\">Analyzed Files</h2>"
f.puts "<ul>"
files.each do |fname, warnings, errors|
readname = fname.split("_")[0...-1].join("_")
f.puts "<li>"
f.puts "<p class=\"file_name\"><a href=\"./#{fname}\">#{readname}</a>"
f.puts "</li>"
end
f.puts "</ul>"
f.string
end
def write_index(files, filename, title, header)
return if files.empty?
File.open(filename,"w") do |f|
f.puts "<html><head><title>#{title}</title></head>"
f.puts "#{HTMLStyleSheet.style_sheet}\n<body>"
f.puts "<h1>#{title}</h1>"
enw = files.find_all { |fn,w,e| (!w.empty? || !e.empty?) }
f.puts summarize_errors_and_warnings(enw, header)
f.puts "<hr/>"
f.puts list_analyzed_files(files)
f.puts "</body></html>"
end
end
def write_cyclo_index(files, output_dir)
header = "<tr><th>Class</th><th>Method</th><th>Complexity</th></tr>"
write_index(files,
"#{output_dir}/index_cyclo.html",
"Index for cyclomatic complexity",
header)
end
def write_token_index(files, output_dir)
header = "<tr><th>File</th><th>Line #</th><th>Tokens</th></tr>"
write_index(files,
"#{output_dir}/index_token.html",
"Index for tokens per line",
header)
end
end
module Saikuro
#Returns the path without the file
def Saikuro.seperate_file_from_path(path)
res = path.split("/")
if res.size == 1
""
else
res[0..res.size - 2].join("/")
end
end
def Saikuro.analyze(files, state_formater, token_count_formater, output_dir)
idx_states = Array.new
idx_tokens = Array.new
# parse each file
files.each do |file|
begin
STDOUT.puts "Parsing #{file}"
# create top state
top = ParseState.make_top_state
STDOUT.puts "TOP State made" if $VERBOSE
token_counter = TokenCounter.new
ParseState.set_token_counter(token_counter)
token_counter.set_current_file(file)
STDOUT.puts "Setting up Lexer" if $VERBOSE
lexer = RubyLex.new
# Turn of this, because it aborts when a syntax error is found...
lexer.exception_on_syntax_error = false
lexer.set_input(File.new(file,"r"))
top.lexer = lexer
STDOUT.puts "Parsing" if $VERBOSE
top.parse
fdir_path = seperate_file_from_path(file)
FileUtils.makedirs("#{output_dir}/#{fdir_path}")
if state_formater
# output results
state_io = StringIO.new
state_formater.start(state_io)
top.compute_state(state_formater)
state_formater.end
fname = "#{file}_cyclo.html"
puts "writing cyclomatic #{file}" if $VERBOSE
File.open("#{output_dir}/#{fname}","w") do |f|
f.write state_io.string
end
idx_states<< [
fname,
state_formater.warnings.dup,
state_formater.errors.dup,
]
end
if token_count_formater
token_io = StringIO.new
token_count_formater.start(token_io)
token_counter.list_tokens_per_line(token_count_formater)
token_count_formater.end
fname = "#{file}_token.html"
puts "writing token #{file}" if $VERBOSE
File.open("#{output_dir}/#{fname}","w") do |f|
f.write token_io.string
end
idx_tokens<< [
fname,
token_count_formater.warnings.dup,
token_count_formater.errors.dup,
]
end
rescue RubyLex::SyntaxError => synerr
STDOUT.puts "Lexer error for file #{file} on line #{lexer.line_no}"
STDOUT.puts "#{synerr.class.name} : #{synerr.message}"
rescue StandardError => err
STDOUT.puts "Error while parsing file : #{file}"
STDOUT.puts err.class,err.message,err.backtrace.join("\n")
rescue Exception => ex
STDOUT.puts "Error while parsing file : #{file}"
STDOUT.puts ex.class,ex.message,ex.backtrace.join("\n")
end
end
[idx_states, idx_tokens]
end
end
# Really ugly command line runner stuff here for now
class SaikuroCMDLineRunner
require 'stringio'
require 'getoptlong'
require 'fileutils'
require 'find'
# modification to RDoc.usage that allows main_program_file to be set
# for RDoc.usage
require 'saikuro/usage'
RDoc::main_program_file = __FILE__
include ResultIndexGenerator
def get_ruby_files(path)
files = Array.new
Find.find(path) do |f|
if !FileTest.directory?(f)
if f =~ /rb$/
files<< f
end
end
end
files
end
def run
files = Array.new
output_dir = "./"
formater = "html"
state_filter = Filter.new(5)
token_filter = Filter.new(10, 25, 50)
comp_state = comp_token = false
begin
opt = GetoptLong.new(
["-o","--output_directory", GetoptLong::REQUIRED_ARGUMENT],
["-h","--help", GetoptLong::NO_ARGUMENT],
["-f","--formater", GetoptLong::REQUIRED_ARGUMENT],
["-c","--cyclo", GetoptLong::NO_ARGUMENT],
["-t","--token", GetoptLong::NO_ARGUMENT],
["-y","--filter_cyclo", GetoptLong::REQUIRED_ARGUMENT],
["-k","--filter_token", GetoptLong::REQUIRED_ARGUMENT],
["-w","--warn_cyclo", GetoptLong::REQUIRED_ARGUMENT],
["-s","--warn_token", GetoptLong::REQUIRED_ARGUMENT],
["-e","--error_cyclo", GetoptLong::REQUIRED_ARGUMENT],
["-d","--error_token", GetoptLong::REQUIRED_ARGUMENT],
["-p","--parse_file", GetoptLong::REQUIRED_ARGUMENT],
["-i","--input_directory", GetoptLong::REQUIRED_ARGUMENT],
["-v","--verbose", GetoptLong::NO_ARGUMENT]
)
opt.each do |arg,val|
case arg
when "-o"
output_dir = val
when "-h"
RDoc.usage('help')
when "-f"
formater = val
when "-c"
comp_state = true
when "-t"
comp_token = true
when "-k"
token_filter.limit = val.to_i
when "-s"
token_filter.warn = val.to_i
when "-d"
token_filter.error = val.to_i
when "-y"
state_filter.limit = val.to_i
when "-w"
state_filter.warn = val.to_i
when "-e"
state_filter.error = val.to_i
when "-p"
files<< val
when "-i"
files.concat(get_ruby_files(val))
when "-v"
STDOUT.puts "Verbose mode on"
$VERBOSE = true
end
end
RDoc.usage if !comp_state && !comp_token
rescue => err
RDoc.usage
end
if formater =~ /html/i
state_formater = StateHTMLComplexityFormater.new(STDOUT,state_filter)
token_count_formater = HTMLTokenCounterFormater.new(STDOUT,token_filter)
else
state_formater = ParseStateFormater.new(STDOUT,state_filter)
token_count_formater = TokenCounterFormater.new(STDOUT,token_filter)
end
state_formater = nil if !comp_state
token_count_formater = nil if !comp_token
idx_states, idx_tokens = Saikuro.analyze(files,
state_formater,
token_count_formater,
output_dir)
write_cyclo_index(idx_states, output_dir)
write_token_index(idx_tokens, output_dir)
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/gems/1.8/gems/Saikuro-1.1.0/lib/saikuro/usage.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/Saikuro-1.1.0/lib/saikuro/usage.rb | # This is a patch to RDoc so that when saikuro is installed as a
# RubyGem usage will read the proper file.
require 'rdoc/usage'
module RDoc
def RDoc.main_program_file=(file)
@@main_program_file = file
end
# Display usage
def RDoc.usage_no_exit(*args)
@@main_program_file ||= caller[-1].sub(/:\d+$/, '')
comment = File.open(@@main_program_file) do |file|
find_comment(file)
end
comment = comment.gsub(/^\s*#/, '')
markup = SM::SimpleMarkup.new
flow_convertor = SM::ToFlow.new
flow = markup.convert(comment, flow_convertor)
format = "plain"
unless args.empty?
flow = extract_sections(flow, args)
end
options = RI::Options.instance
if args = ENV["RI"]
options.parse(args.split)
end
formatter = options.formatter.new(options, "")
formatter.display_flow(flow)
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/gems/1.8/gems/json_pure-1.4.6/install.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/install.rb | #!/usr/bin/env ruby
require 'rbconfig'
require 'fileutils'
include FileUtils::Verbose
include Config
bindir = CONFIG["bindir"]
cd 'bin' do
filename = 'edit_json.rb'
#install(filename, bindir)
end
sitelibdir = CONFIG["sitelibdir"]
cd 'lib' do
install('json.rb', sitelibdir)
mkdir_p File.join(sitelibdir, 'json')
for file in Dir['json/**/*.{rb,xpm}']
d = File.join(sitelibdir, file)
mkdir_p File.dirname(d)
install(file, d)
end
install(File.join('json', 'editor.rb'), File.join(sitelibdir,'json'))
install(File.join('json', 'json.xpm'), File.join(sitelibdir,'json'))
end
warn " *** Installed PURE ruby library."
| 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/gems/1.8/gems/json_pure-1.4.6/benchmarks/parser2_benchmark.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/benchmarks/parser2_benchmark.rb | #!/usr/bin/env ruby
# CODING: UTF-8
require 'rbconfig'
RUBY_PATH=File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
RAKE_PATH=File.join(Config::CONFIG['bindir'], 'rake')
require 'bullshit'
case ARGV.first
when 'ext'
require 'json/ext'
when 'pure'
require 'json/pure'
when 'yaml'
require 'yaml'
require 'json/pure'
when 'rails'
require 'active_support'
require 'json/pure'
when 'yajl'
require 'yajl'
require 'json/pure'
else
require 'json/pure'
end
module Parser2BenchmarkCommon
include JSON
def setup
@big = @json = File.read(File.join(File.dirname(__FILE__), 'ohai.json'))
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class Parser2BenchmarkExt < Bullshit::RepeatCase
include Parser2BenchmarkCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_parser
@result = JSON.parse(@json)
end
alias reset_parser generic_reset_method
def benchmark_parser_symbolic
@result = JSON.parse(@json, :symbolize_names => true)
end
alias reset_parser_symbolc generic_reset_method
end
class Parser2BenchmarkPure < Bullshit::RepeatCase
include Parser2BenchmarkCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_parser
@result = JSON.parse(@json)
end
alias reset_parser generic_reset_method
def benchmark_parser_symbolic
@result = JSON.parse(@json, :symbolize_names => true)
end
alias reset_parser_symbolc generic_reset_method
end
class Parser2BenchmarkYAML < Bullshit::RepeatCase
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
@big = @json = File.read(File.join(File.dirname(__FILE__), 'ohai.json'))
end
def benchmark_parser
@result = YAML.load(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class Parser2BenchmarkRails < Bullshit::RepeatCase
warmup yes
iterations 400
truncate_data do
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.generate(@big)
end
def benchmark_parser
@result = ActiveSupport::JSON.decode(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class Parser2BenchmarkYajl < Bullshit::RepeatCase
warmup yes
iterations 2000
truncate_data do
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
@big = @json = File.read(File.join(File.dirname(__FILE__), 'ohai.json'))
end
def benchmark_parser
@result = Yajl::Parser.new.parse(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
if $0 == __FILE__
Bullshit::Case.autorun false
case ARGV.first
when 'ext'
Parser2BenchmarkExt.run
when 'pure'
Parser2BenchmarkPure.run
when 'yaml'
Parser2BenchmarkYAML.run
when 'rails'
Parser2BenchmarkRails.run
when 'yajl'
Parser2BenchmarkYajl.run
else
system "#{RAKE_PATH} clean"
system "#{RUBY_PATH} #$0 yaml"
system "#{RUBY_PATH} #$0 rails"
system "#{RUBY_PATH} #$0 pure"
system "#{RAKE_PATH} compile_ext"
system "#{RUBY_PATH} #$0 ext"
system "#{RUBY_PATH} #$0 yajl"
Bullshit.compare do
output_filename File.join(File.dirname(__FILE__), 'data', 'Parser2BenchmarkComparison.log')
benchmark Parser2BenchmarkExt, :parser, :load => yes
benchmark Parser2BenchmarkExt, :parser_symbolic, :load => yes
benchmark Parser2BenchmarkPure, :parser, :load => yes
benchmark Parser2BenchmarkPure, :parser_symbolic, :load => yes
benchmark Parser2BenchmarkYAML, :parser, :load => yes
benchmark Parser2BenchmarkRails, :parser, :load => yes
benchmark Parser2BenchmarkYajl, :parser, :load => yes
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/gems/1.8/gems/json_pure-1.4.6/benchmarks/parser_benchmark.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/benchmarks/parser_benchmark.rb | #!/usr/bin/env ruby
# CODING: UTF-8
require 'rbconfig'
RUBY_PATH=File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
RAKE_PATH=File.join(Config::CONFIG['bindir'], 'rake')
require 'bullshit'
case ARGV.first
when 'ext'
require 'json/ext'
when 'pure'
require 'json/pure'
when 'yaml'
require 'yaml'
require 'json/pure'
when 'rails'
require 'active_support'
require 'json/pure'
when 'yajl'
require 'yajl'
require 'json/pure'
else
require 'json/pure'
end
module ParserBenchmarkCommon
include JSON
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.generate(@big)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class ParserBenchmarkExt < Bullshit::RepeatCase
include ParserBenchmarkCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_parser
@result = JSON.parse(@json)
end
alias reset_parser generic_reset_method
def benchmark_parser_symbolic
@result = JSON.parse(@json, :symbolize_names => true)
end
alias reset_parser_symbolc generic_reset_method
end
class ParserBenchmarkPure < Bullshit::RepeatCase
include ParserBenchmarkCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_parser
@result = JSON.parse(@json)
end
alias reset_parser generic_reset_method
def benchmark_parser_symbolic
@result = JSON.parse(@json, :symbolize_names => true)
end
alias reset_parser_symbolc generic_reset_method
end
class ParserBenchmarkYAML < Bullshit::RepeatCase
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.pretty_generate(@big)
end
def benchmark_parser
@result = YAML.load(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class ParserBenchmarkRails < Bullshit::RepeatCase
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.generate(@big)
end
def benchmark_parser
@result = ActiveSupport::JSON.decode(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
class ParserBenchmarkYajl < Bullshit::RepeatCase
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def setup
a = [ nil, false, true, "fÖß\nÄr", [ "n€st€d", true ], { "fooß" => "bär", "qu\r\nux" => true } ]
@big = a * 100
@json = JSON.generate(@big)
end
def benchmark_parser
@result = Yajl::Parser.new.parse(@json)
end
def generic_reset_method
@result == @big or raise "not equal"
end
end
if $0 == __FILE__
Bullshit::Case.autorun false
case ARGV.first
when 'ext'
ParserBenchmarkExt.run
when 'pure'
ParserBenchmarkPure.run
when 'yaml'
ParserBenchmarkYAML.run
when 'rails'
ParserBenchmarkRails.run
when 'yajl'
ParserBenchmarkYajl.run
else
system "#{RAKE_PATH} clean"
system "#{RUBY_PATH} #$0 yaml"
system "#{RUBY_PATH} #$0 rails"
system "#{RUBY_PATH} #$0 pure"
system "#{RAKE_PATH} compile_ext"
system "#{RUBY_PATH} #$0 ext"
system "#{RUBY_PATH} #$0 yajl"
Bullshit.compare do
output_filename File.join(File.dirname(__FILE__), 'data', 'ParserBenchmarkComparison.log')
benchmark ParserBenchmarkExt, :parser, :load => yes
benchmark ParserBenchmarkExt, :parser_symbolic, :load => yes
benchmark ParserBenchmarkPure, :parser, :load => yes
benchmark ParserBenchmarkPure, :parser_symbolic, :load => yes
benchmark ParserBenchmarkYAML, :parser, :load => yes
benchmark ParserBenchmarkRails, :parser, :load => yes
benchmark ParserBenchmarkYajl, :parser, :load => yes
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/gems/1.8/gems/json_pure-1.4.6/benchmarks/generator2_benchmark.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/benchmarks/generator2_benchmark.rb | #!/usr/bin/env ruby
# CODING: UTF-8
require 'rbconfig'
RUBY_PATH=File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
RAKE_PATH=File.join(Config::CONFIG['bindir'], 'rake')
require 'bullshit'
case ARGV.first
when 'ext'
require 'json/ext'
when 'pure'
require 'json/pure'
when 'rails'
require 'active_support'
when 'yajl'
require 'yajl'
require 'yajl/json_gem'
require 'stringio'
end
module JSON
def self.[](*) end
end
module Generator2BenchmarkCommon
include JSON
def setup
@big = eval File.read(File.join(File.dirname(__FILE__), 'ohai.ruby'))
end
def generic_reset_method
@result and @result.size >= 16 or raise @result.to_s
end
end
module JSONGeneratorCommon
include Generator2BenchmarkCommon
def benchmark_generator_fast
@result = JSON.fast_generate(@big)
end
alias reset_benchmark_generator_fast generic_reset_method
def benchmark_generator_safe
@result = JSON.generate(@big)
end
alias reset_benchmark_generator_safe generic_reset_method
def benchmark_generator_pretty
@result = JSON.pretty_generate(@big)
end
alias reset_benchmark_generator_pretty generic_reset_method
def benchmark_generator_ascii
@result = JSON.generate(@big, :ascii_only => true)
end
alias reset_benchmark_generator_ascii generic_reset_method
end
class Generator2BenchmarkExt < Bullshit::RepeatCase
include JSONGeneratorCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
end
class Generator2BenchmarkPure < Bullshit::RepeatCase
include JSONGeneratorCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
end
class Generator2BenchmarkRails < Bullshit::RepeatCase
include Generator2BenchmarkCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_generator
@result = @big.to_json
end
alias reset_benchmark_generator generic_reset_method
end
class Generator2BenchmarkYajl < Bullshit::RepeatCase
include Generator2BenchmarkCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_generator
output = StringIO.new
Yajl::Encoder.new.encode(@big, output)
@result = output.string
end
def benchmark_generator_gem_api
@result = @big.to_json
end
def reset_benchmark_generator
generic_reset_method
end
end
if $0 == __FILE__
Bullshit::Case.autorun false
case ARGV.first
when 'ext'
Generator2BenchmarkExt.run
when 'pure'
Generator2BenchmarkPure.run
when 'rails'
Generator2BenchmarkRails.run
when 'yajl'
Generator2BenchmarkYajl.run
else
system "#{RAKE_PATH} clean"
system "#{RUBY_PATH} #$0 rails"
system "#{RUBY_PATH} #$0 pure"
system "#{RAKE_PATH} compile_ext"
system "#{RUBY_PATH} #$0 ext"
system "#{RUBY_PATH} #$0 yajl"
Bullshit.compare do
output_filename File.join(File.dirname(__FILE__), 'data', 'Generator2BenchmarkComparison.log')
benchmark Generator2BenchmarkExt, :generator_fast, :load => yes
benchmark Generator2BenchmarkExt, :generator_safe, :load => yes
benchmark Generator2BenchmarkExt, :generator_pretty, :load => yes
benchmark Generator2BenchmarkExt, :generator_ascii, :load => yes
benchmark Generator2BenchmarkPure, :generator_fast, :load => yes
benchmark Generator2BenchmarkPure, :generator_safe, :load => yes
benchmark Generator2BenchmarkPure, :generator_pretty, :load => yes
benchmark Generator2BenchmarkPure, :generator_ascii, :load => yes
benchmark Generator2BenchmarkRails, :generator, :load => yes
benchmark Generator2BenchmarkYajl, :generator, :load => yes
benchmark Generator2BenchmarkYajl, :generator_gem_api, :load => yes
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/gems/1.8/gems/json_pure-1.4.6/benchmarks/generator_benchmark.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/benchmarks/generator_benchmark.rb | #!/usr/bin/env ruby
# CODING: UTF-8
require 'rbconfig'
RUBY_PATH=File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
RAKE_PATH=File.join(Config::CONFIG['bindir'], 'rake')
require 'bullshit'
case ARGV.first
when 'ext'
require 'json/ext'
when 'pure'
require 'json/pure'
when 'rails'
require 'active_support'
when 'yajl'
require 'yajl'
require 'yajl/json_gem'
require 'stringio'
end
module JSON
def self.[](*) end
end
module GeneratorBenchmarkCommon
include JSON
def setup
a = [ nil, false, true, "fÖßÄr", [ "n€st€d", true ], { "fooß" => "bär", "quux" => true } ]
puts a.to_json if a.respond_to?(:to_json)
@big = a * 100
end
def generic_reset_method
@result and @result.size > 2 + 6 * @big.size or raise @result.to_s
end
end
module JSONGeneratorCommon
include GeneratorBenchmarkCommon
def benchmark_generator_fast
@result = JSON.fast_generate(@big)
end
alias reset_benchmark_generator_fast generic_reset_method
def benchmark_generator_safe
@result = JSON.generate(@big)
end
alias reset_benchmark_generator_safe generic_reset_method
def benchmark_generator_pretty
@result = JSON.pretty_generate(@big)
end
alias reset_benchmark_generator_pretty generic_reset_method
def benchmark_generator_ascii
@result = JSON.generate(@big, :ascii_only => true)
end
alias reset_benchmark_generator_ascii generic_reset_method
end
class GeneratorBenchmarkExt < Bullshit::RepeatCase
include JSONGeneratorCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
end
class GeneratorBenchmarkPure < Bullshit::RepeatCase
include JSONGeneratorCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
end
class GeneratorBenchmarkRails < Bullshit::RepeatCase
include GeneratorBenchmarkCommon
warmup yes
iterations 400
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_generator
@result = @big.to_json
end
alias reset_benchmark_generator generic_reset_method
end
class GeneratorBenchmarkYajl < Bullshit::RepeatCase
include GeneratorBenchmarkCommon
warmup yes
iterations 2000
truncate_data do
enabled false
alpha_level 0.05
window_size 50
slope_angle 0.1
end
autocorrelation do
alpha_level 0.05
max_lags 50
file yes
end
output_dir File.join(File.dirname(__FILE__), 'data')
output_filename benchmark_name + '.log'
data_file yes
histogram yes
def benchmark_generator
output = StringIO.new
Yajl::Encoder.new.encode(@big, output)
@result = output.string
end
def benchmark_generator_gem_api
@result = @big.to_json
end
def reset_benchmark_generator
generic_reset_method
end
end
if $0 == __FILE__
Bullshit::Case.autorun false
case ARGV.first
when 'ext'
GeneratorBenchmarkExt.run
when 'pure'
GeneratorBenchmarkPure.run
when 'rails'
GeneratorBenchmarkRails.run
when 'yajl'
GeneratorBenchmarkYajl.run
else
system "#{RAKE_PATH} clean"
system "#{RUBY_PATH} #$0 rails"
system "#{RUBY_PATH} #$0 pure"
system "#{RAKE_PATH} compile_ext"
system "#{RUBY_PATH} #$0 ext"
system "#{RUBY_PATH} #$0 yajl"
Bullshit.compare do
output_filename File.join(File.dirname(__FILE__), 'data', 'GeneratorBenchmarkComparison.log')
benchmark GeneratorBenchmarkExt, :generator_fast, :load => yes
benchmark GeneratorBenchmarkExt, :generator_safe, :load => yes
benchmark GeneratorBenchmarkExt, :generator_pretty, :load => yes
benchmark GeneratorBenchmarkExt, :generator_ascii, :load => yes
benchmark GeneratorBenchmarkPure, :generator_fast, :load => yes
benchmark GeneratorBenchmarkPure, :generator_safe, :load => yes
benchmark GeneratorBenchmarkPure, :generator_pretty, :load => yes
benchmark GeneratorBenchmarkPure, :generator_ascii, :load => yes
benchmark GeneratorBenchmarkRails, :generator, :load => yes
benchmark GeneratorBenchmarkYajl, :generator, :load => yes
benchmark GeneratorBenchmarkYajl, :generator_gem_api, :load => yes
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/gems/1.8/gems/json_pure-1.4.6/tools/fuzz.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/tools/fuzz.rb | require 'json'
require 'iconv'
ISO_8859_1_TO_UTF8 = Iconv.new('utf-8', 'iso-8859-15')
class ::String
def to_utf8
ISO_8859_1_TO_UTF8.iconv self
end
end
class Fuzzer
def initialize(n, freqs = {})
sum = freqs.inject(0.0) { |s, x| s + x.last }
freqs.each_key { |x| freqs[x] /= sum }
s = 0.0
freqs.each_key do |x|
freqs[x] = s .. (s + t = freqs[x])
s += t
end
@freqs = freqs
@n = n
@alpha = (0..0xff).to_a
end
def random_string
s = ''
30.times { s << @alpha[rand(@alpha.size)] }
s.to_utf8
end
def pick
r = rand
found = @freqs.find { |k, f| f.include? rand }
found && found.first
end
def make_pick
k = pick
case
when k == Hash, k == Array
k.new
when k == true, k == false, k == nil
k
when k == String
random_string
when k == Fixnum
rand(2 ** 30) - 2 ** 29
when k == Bignum
rand(2 ** 70) - 2 ** 69
end
end
def fuzz(current = nil)
if @n > 0
case current
when nil
@n -= 1
current = fuzz [ Hash, Array ][rand(2)].new
when Array
while @n > 0
@n -= 1
current << case p = make_pick
when Array, Hash
fuzz(p)
else
p
end
end
when Hash
while @n > 0
@n -= 1
current[random_string] = case p = make_pick
when Array, Hash
fuzz(p)
else
p
end
end
end
end
current
end
end
class MyState < JSON.state
WS = " \r\t\n"
def initialize
super(
:indent => make_spaces,
:space => make_spaces,
:space_before => make_spaces,
:object_nl => make_spaces,
:array_nl => make_spaces,
:max_nesting => false
)
end
def make_spaces
s = ''
rand(1).times { s << WS[rand(WS.size)] }
s
end
end
n = (ARGV.shift || 500).to_i
loop do
fuzzer = Fuzzer.new(n,
Hash => 25,
Array => 25,
String => 10,
Fixnum => 10,
Bignum => 10,
nil => 5,
true => 5,
false => 5
)
o1 = fuzzer.fuzz
json = JSON.generate o1, MyState.new
if $DEBUG
puts "-" * 80
puts json, json.size
else
puts json.size
end
begin
o2 = JSON.parse(json, :max_nesting => false)
rescue JSON::ParserError => e
puts "Caught #{e.class}: #{e.message}\n#{e.backtrace * "\n"}"
puts "o1 = #{o1.inspect}", "json = #{json}", "json_str = #{json.inspect}"
puts "locals = #{local_variables.inspect}"
exit
end
if o1 != o2
puts "mismatch", "o1 = #{o1.inspect}", "o2 = #{o2.inspect}",
"json = #{json}", "json_str = #{json.inspect}"
puts "locals = #{local_variables.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/gems/1.8/gems/json_pure-1.4.6/tools/server.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/tools/server.rb | #!/usr/bin/env ruby
require 'webrick'
include WEBrick
$:.unshift 'ext'
$:.unshift 'lib'
require 'json'
class JSONServlet < HTTPServlet::AbstractServlet
@@count = 1
def do_GET(req, res)
obj = {
"TIME" => Time.now.strftime("%FT%T"),
"foo" => "Bär",
"bar" => "© ≠ €!",
'a' => 2,
'b' => 3.141,
'COUNT' => @@count += 1,
'c' => 'c',
'd' => [ 1, "b", 3.14 ],
'e' => { 'foo' => 'bar' },
'g' => "松本行弘",
'h' => 1000.0,
'i' => 0.001,
'j' => "\xf0\xa0\x80\x81",
}
res.body = JSON.generate obj
res['Content-Type'] = "application/json"
end
end
def create_server(err, dir, port)
dir = File.expand_path(dir)
err.puts "Surf to:", "http://#{Socket.gethostname}:#{port}"
s = HTTPServer.new(
:Port => port,
:DocumentRoot => dir,
:Logger => WEBrick::Log.new(err),
:AccessLog => [
[ err, WEBrick::AccessLog::COMMON_LOG_FORMAT ],
[ err, WEBrick::AccessLog::REFERER_LOG_FORMAT ],
[ err, WEBrick::AccessLog::AGENT_LOG_FORMAT ]
]
)
s.mount("/json", JSONServlet)
s
end
default_dir = File.expand_path(File.join(File.dirname(__FILE__), '..', 'data'))
dir = ARGV.shift || default_dir
port = (ARGV.shift || 6666).to_i
s = create_server(STDERR, dir, 6666)
t = Thread.new { s.start }
trap(:INT) do
s.shutdown
t.join
exit
end
sleep
| 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/gems/1.8/gems/json_pure-1.4.6/tests/test_json_generate.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/tests/test_json_generate.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
class TC_JSONGenerate < Test::Unit::TestCase
include JSON
def setup
@hash = {
'a' => 2,
'b' => 3.141,
'c' => 'c',
'd' => [ 1, "b", 3.14 ],
'e' => { 'foo' => 'bar' },
'g' => "\"\0\037",
'h' => 1000.0,
'i' => 0.001
}
@json2 = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},' +
'"g":"\\"\\u0000\\u001f","h":1000.0,"i":0.001}'
@json3 = <<'EOT'.chomp
{
"a": 2,
"b": 3.141,
"c": "c",
"d": [
1,
"b",
3.14
],
"e": {
"foo": "bar"
},
"g": "\"\u0000\u001f",
"h": 1000.0,
"i": 0.001
}
EOT
end
def test_generate
json = generate(@hash)
assert_equal(JSON.parse(@json2), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = generate({1=>2})
assert_equal('{"1":2}', json)
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { generate(666) }
end
def test_generate_pretty
json = pretty_generate(@hash)
assert_equal(JSON.parse(@json3), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = pretty_generate({1=>2})
assert_equal(<<'EOT'.chomp, json)
{
"1": 2
}
EOT
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { pretty_generate(666) }
end
def test_fast_generate
json = fast_generate(@hash)
assert_equal(JSON.parse(@json2), JSON.parse(json))
parsed_json = parse(json)
assert_equal(@hash, parsed_json)
json = fast_generate({1=>2})
assert_equal('{"1":2}', json)
parsed_json = parse(json)
assert_equal({"1"=>2}, parsed_json)
assert_raise(GeneratorError) { fast_generate(666) }
end
def test_states
json = generate({1=>2}, nil)
assert_equal('{"1":2}', json)
s = JSON.state.new
assert s.check_circular?
assert s[:check_circular?]
h = { 1=>2 }
h[3] = h
assert_raises(JSON::NestingError) { generate(h) }
assert_raises(JSON::NestingError) { generate(h, s) }
s = JSON.state.new
a = [ 1, 2 ]
a << a
assert_raises(JSON::NestingError) { generate(a, s) }
assert s.check_circular?
assert s[:check_circular?]
end
def test_pretty_state
state = PRETTY_STATE_PROTOTYPE.dup
assert_equal({
:allow_nan => false,
:array_nl => "\n",
:ascii_only => false,
:depth => 0,
:indent => " ",
:max_nesting => 19,
:object_nl => "\n",
:space => " ",
:space_before => "",
}.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s })
end
def test_safe_state
state = SAFE_STATE_PROTOTYPE.dup
assert_equal({
:allow_nan => false,
:array_nl => "",
:ascii_only => false,
:depth => 0,
:indent => "",
:max_nesting => 19,
:object_nl => "",
:space => "",
:space_before => "",
}.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s })
end
def test_fast_state
state = FAST_STATE_PROTOTYPE.dup
assert_equal({
:allow_nan => false,
:array_nl => "",
:ascii_only => false,
:depth => 0,
:indent => "",
:max_nesting => 0,
:object_nl => "",
:space => "",
:space_before => "",
}.sort_by { |n,| n.to_s }, state.to_h.sort_by { |n,| n.to_s })
end
def test_allow_nan
assert_raises(GeneratorError) { generate([JSON::NaN]) }
assert_equal '[NaN]', generate([JSON::NaN], :allow_nan => true)
assert_raises(GeneratorError) { fast_generate([JSON::NaN]) }
assert_raises(GeneratorError) { pretty_generate([JSON::NaN]) }
assert_equal "[\n NaN\n]", pretty_generate([JSON::NaN], :allow_nan => true)
assert_raises(GeneratorError) { generate([JSON::Infinity]) }
assert_equal '[Infinity]', generate([JSON::Infinity], :allow_nan => true)
assert_raises(GeneratorError) { fast_generate([JSON::Infinity]) }
assert_raises(GeneratorError) { pretty_generate([JSON::Infinity]) }
assert_equal "[\n Infinity\n]", pretty_generate([JSON::Infinity], :allow_nan => true)
assert_raises(GeneratorError) { generate([JSON::MinusInfinity]) }
assert_equal '[-Infinity]', generate([JSON::MinusInfinity], :allow_nan => true)
assert_raises(GeneratorError) { fast_generate([JSON::MinusInfinity]) }
assert_raises(GeneratorError) { pretty_generate([JSON::MinusInfinity]) }
assert_equal "[\n -Infinity\n]", pretty_generate([JSON::MinusInfinity], :allow_nan => true)
end
def test_depth
ary = []; ary << ary
assert_equal 0, JSON::SAFE_STATE_PROTOTYPE.depth
assert_raises(JSON::NestingError) { JSON.generate(ary) }
assert_equal 0, JSON::SAFE_STATE_PROTOTYPE.depth
assert_equal 0, JSON::PRETTY_STATE_PROTOTYPE.depth
assert_raises(JSON::NestingError) { JSON.pretty_generate(ary) }
assert_equal 0, JSON::PRETTY_STATE_PROTOTYPE.depth
s = JSON.state.new
assert_equal 0, s.depth
assert_raises(JSON::NestingError) { ary.to_json(s) }
assert_equal 19, s.depth
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/gems/1.8/gems/json_pure-1.4.6/tests/test_json_encoding.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/tests/test_json_encoding.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
require 'iconv'
class TC_JSONEncoding < Test::Unit::TestCase
include JSON
def setup
@utf_8 = '["© ≠ €!"]'
@parsed = [ "© ≠ €!" ]
@utf_16_data = Iconv.iconv('utf-16be', 'utf-8', @parsed.first)
@generated = '["\u00a9 \u2260 \u20ac!"]'
if defined?(::Encoding)
@utf_8_ascii_8bit = @utf_8.dup.force_encoding(Encoding::ASCII_8BIT)
@utf_16be, = Iconv.iconv('utf-16be', 'utf-8', @utf_8)
@utf_16be_ascii_8bit = @utf_16be.dup.force_encoding(Encoding::ASCII_8BIT)
@utf_16le, = Iconv.iconv('utf-16le', 'utf-8', @utf_8)
@utf_16le_ascii_8bit = @utf_16le.dup.force_encoding(Encoding::ASCII_8BIT)
@utf_32be, = Iconv.iconv('utf-32be', 'utf-8', @utf_8)
@utf_32be_ascii_8bit = @utf_32be.dup.force_encoding(Encoding::ASCII_8BIT)
@utf_32le, = Iconv.iconv('utf-32le', 'utf-8', @utf_8)
@utf_32le_ascii_8bit = @utf_32le.dup.force_encoding(Encoding::ASCII_8BIT)
else
@utf_8_ascii_8bit = @utf_8.dup
@utf_16be, = Iconv.iconv('utf-16be', 'utf-8', @utf_8)
@utf_16be_ascii_8bit = @utf_16be.dup
@utf_16le, = Iconv.iconv('utf-16le', 'utf-8', @utf_8)
@utf_16le_ascii_8bit = @utf_16le.dup
@utf_32be, = Iconv.iconv('utf-32be', 'utf-8', @utf_8)
@utf_32be_ascii_8bit = @utf_32be.dup
@utf_32le, = Iconv.iconv('utf-32le', 'utf-8', @utf_8)
@utf_32le_ascii_8bit = @utf_32le.dup
end
end
def test_parse
assert_equal @parsed, JSON.parse(@utf_8)
assert_equal @parsed, JSON.parse(@utf_16be)
assert_equal @parsed, JSON.parse(@utf_16le)
assert_equal @parsed, JSON.parse(@utf_32be)
assert_equal @parsed, JSON.parse(@utf_32le)
end
def test_parse_ascii_8bit
assert_equal @parsed, JSON.parse(@utf_8_ascii_8bit)
assert_equal @parsed, JSON.parse(@utf_16be_ascii_8bit)
assert_equal @parsed, JSON.parse(@utf_16le_ascii_8bit)
assert_equal @parsed, JSON.parse(@utf_32be_ascii_8bit)
assert_equal @parsed, JSON.parse(@utf_32le_ascii_8bit)
end
def test_generate
assert_equal @generated, JSON.generate(@parsed, :ascii_only => true)
if defined?(::Encoding)
assert_equal @generated, JSON.generate(@utf_16_data, :ascii_only => true)
else
# XXX checking of correct utf8 data is not as strict (yet?) without :ascii_only
assert_raises(JSON::GeneratorError) { JSON.generate(@utf_16_data, :ascii_only => true) }
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/gems/1.8/gems/json_pure-1.4.6/tests/test_json_unicode.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/tests/test_json_unicode.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
class TC_JSONUnicode < Test::Unit::TestCase
include JSON
def test_unicode
assert_equal '""', ''.to_json
assert_equal '"\\b"', "\b".to_json
assert_equal '"\u0001"', 0x1.chr.to_json
assert_equal '"\u001f"', 0x1f.chr.to_json
assert_equal '" "', ' '.to_json
assert_equal "\"#{0x7f.chr}\"", 0x7f.chr.to_json
utf8 = [ "© ≠ €! \01" ]
json = '["© ≠ €! \u0001"]'
assert_equal json, utf8.to_json(:ascii_only => false)
assert_equal utf8, parse(json)
json = '["\u00a9 \u2260 \u20ac! \u0001"]'
assert_equal json, utf8.to_json(:ascii_only => true)
assert_equal utf8, parse(json)
utf8 = ["\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212"]
json = "[\"\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212\"]"
assert_equal utf8, parse(json)
assert_equal json, utf8.to_json(:ascii_only => false)
utf8 = ["\343\201\202\343\201\204\343\201\206\343\201\210\343\201\212"]
assert_equal utf8, parse(json)
json = "[\"\\u3042\\u3044\\u3046\\u3048\\u304a\"]"
assert_equal json, utf8.to_json(:ascii_only => true)
assert_equal utf8, parse(json)
utf8 = ['საქართველო']
json = '["საქართველო"]'
assert_equal json, utf8.to_json(:ascii_only => false)
json = "[\"\\u10e1\\u10d0\\u10e5\\u10d0\\u10e0\\u10d7\\u10d5\\u10d4\\u10da\\u10dd\"]"
assert_equal json, utf8.to_json(:ascii_only => true)
assert_equal utf8, parse(json)
assert_equal '["Ã"]', JSON.generate(["Ã"], :ascii_only => false)
assert_equal '["\\u00c3"]', JSON.generate(["Ã"], :ascii_only => true)
assert_equal ["€"], JSON.parse('["\u20ac"]')
utf8 = ["\xf0\xa0\x80\x81"]
json = "[\"\xf0\xa0\x80\x81\"]"
assert_equal json, JSON.generate(utf8, :ascii_only => false)
assert_equal utf8, JSON.parse(json)
json = '["\ud840\udc01"]'
assert_equal json, JSON.generate(utf8, :ascii_only => true)
assert_equal utf8, JSON.parse(json)
end
def test_chars
(0..0x7f).each do |i|
json = '["\u%04x"]' % i
if RUBY_VERSION >= "1.9."
i = i.chr
end
assert_equal i, JSON.parse(json).first[0]
if i == ?\b
generated = JSON.generate(["" << i])
assert '["\b"]' == generated || '["\10"]' == generated
elsif [?\n, ?\r, ?\t, ?\f].include?(i)
assert_equal '[' << ('' << i).dump << ']', JSON.generate(["" << i])
elsif i.chr < 0x20.chr
assert_equal json, JSON.generate(["" << i])
end
end
assert_raise(JSON::GeneratorError) do
JSON.generate(["\x80"], :ascii_only => true)
end
assert_equal "\302\200", JSON.parse('["\u0080"]').first
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/gems/1.8/gems/json_pure-1.4.6/tests/test_json_fixtures.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/tests/test_json_fixtures.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
class TC_JSONFixtures < Test::Unit::TestCase
def setup
fixtures = File.join(File.dirname(__FILE__), 'fixtures/*.json')
passed, failed = Dir[fixtures].partition { |f| f['pass'] }
@passed = passed.inject([]) { |a, f| a << [ f, File.read(f) ] }.sort
@failed = failed.inject([]) { |a, f| a << [ f, File.read(f) ] }.sort
end
def test_passing
for name, source in @passed
assert JSON.parse(source),
"Did not pass for fixture '#{name}'"
end
end
def test_failing
for name, source in @failed
assert_raises(JSON::ParserError, JSON::NestingError,
"Did not fail for fixture '#{name}'") do
JSON.parse(source)
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/gems/1.8/gems/json_pure-1.4.6/tests/test_json_rails.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/tests/test_json_rails.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
require 'json/add/rails'
require 'date'
class TC_JSONRails < Test::Unit::TestCase
include JSON
class A
def initialize(a)
@a = a
end
attr_reader :a
def ==(other)
a == other.a
end
def self.json_create(object)
new(*object['args'])
end
def to_json(*args)
{
'json_class' => self.class.name,
'args' => [ @a ],
}.to_json(*args)
end
end
class B
def self.json_creatable?
false
end
def to_json(*args)
{
'json_class' => self.class.name,
}.to_json(*args)
end
end
class C
def to_json(*args)
{
'json_class' => 'TC_JSONRails::Nix',
}.to_json(*args)
end
end
class D
def initialize
@foo = 666
end
attr_reader :foo
def ==(other)
foo == other.foo
end
end
def test_extended_json
a = A.new(666)
assert A.json_creatable?
assert_equal 666, a.a
json = generate(a)
a_again = JSON.parse(json)
assert_kind_of a.class, a_again
assert_equal a, a_again
assert_equal 666, a_again.a
end
def test_extended_json_generic_object
d = D.new
assert D.json_creatable?
assert_equal 666, d.foo
json = generate(d)
d_again = JSON.parse(json)
assert_kind_of d.class, d_again
assert_equal d, d_again
assert_equal 666, d_again.foo
end
def test_extended_json_disabled
a = A.new(666)
assert A.json_creatable?
json = generate(a)
a_again = JSON.parse(json, :create_additions => true)
assert_kind_of a.class, a_again
assert_equal a, a_again
a_hash = JSON.parse(json, :create_additions => false)
assert_kind_of Hash, a_hash
assert_equal(
{"args"=>[666], "json_class"=>"TC_JSONRails::A"}.sort_by { |k,| k },
a_hash.sort_by { |k,| k }
)
end
def test_extended_json_fail1
b = B.new
assert !B.json_creatable?
json = generate(b)
assert_equal({ 'json_class' => B.name }, JSON.parse(json))
end
def test_extended_json_fail2
c = C.new # with rails addition all objects are theoretically creatable
assert C.json_creatable?
json = generate(c)
assert_raises(ArgumentError, NameError) { JSON.parse(json) }
end
def test_raw_strings
raw = ''
raw.respond_to?(:encode!) and raw.encode!(Encoding::ASCII_8BIT)
raw_array = []
for i in 0..255
raw << i
raw_array << i
end
json = raw.to_json_raw
json_raw_object = raw.to_json_raw_object
hash = { 'json_class' => 'String', 'raw'=> raw_array }
assert_equal hash, json_raw_object
assert_match /\A\{.*\}\Z/, json
assert_match /"json_class":"String"/, json
assert_match /"raw":\[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json
raw_again = JSON.parse(json)
assert_equal raw, raw_again
end
def test_symbol
assert_equal '"foo"', :foo.to_json # we don't want an object here
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/gems/1.8/gems/json_pure-1.4.6/tests/test_json_addition.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/tests/test_json_addition.rb | #!/usr/bin/env ruby
# -*- coding:utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
require 'json/add/core'
require 'date'
class TC_JSONAddition < Test::Unit::TestCase
include JSON
class A
def initialize(a)
@a = a
end
attr_reader :a
def ==(other)
a == other.a
end
def self.json_create(object)
new(*object['args'])
end
def to_json(*args)
{
'json_class' => self.class.name,
'args' => [ @a ],
}.to_json(*args)
end
end
class B
def self.json_creatable?
false
end
def to_json(*args)
{
'json_class' => self.class.name,
}.to_json(*args)
end
end
class C
def self.json_creatable?
false
end
def to_json(*args)
{
'json_class' => 'TC_JSONAddition::Nix',
}.to_json(*args)
end
end
def test_extended_json
a = A.new(666)
assert A.json_creatable?
json = generate(a)
a_again = JSON.parse(json)
assert_kind_of a.class, a_again
assert_equal a, a_again
end
def test_extended_json_disabled
a = A.new(666)
assert A.json_creatable?
json = generate(a)
a_again = JSON.parse(json, :create_additions => true)
assert_kind_of a.class, a_again
assert_equal a, a_again
a_hash = JSON.parse(json, :create_additions => false)
assert_kind_of Hash, a_hash
assert_equal(
{"args"=>[666], "json_class"=>"TC_JSONAddition::A"}.sort_by { |k,| k },
a_hash.sort_by { |k,| k }
)
end
def test_extended_json_fail1
b = B.new
assert !B.json_creatable?
json = generate(b)
assert_equal({ "json_class"=>"TC_JSONAddition::B" }, JSON.parse(json))
end
def test_extended_json_fail2
c = C.new
assert !C.json_creatable?
json = generate(c)
assert_raises(ArgumentError, NameError) { JSON.parse(json) }
end
def test_raw_strings
raw = ''
raw.respond_to?(:encode!) and raw.encode!(Encoding::ASCII_8BIT)
raw_array = []
for i in 0..255
raw << i
raw_array << i
end
json = raw.to_json_raw
json_raw_object = raw.to_json_raw_object
hash = { 'json_class' => 'String', 'raw'=> raw_array }
assert_equal hash, json_raw_object
assert_match /\A\{.*\}\Z/, json
assert_match /"json_class":"String"/, json
assert_match /"raw":\[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255\]/, json
raw_again = JSON.parse(json)
assert_equal raw, raw_again
end
MyJsonStruct = Struct.new 'MyJsonStruct', :foo, :bar
def test_core
t = Time.now
assert_equal t.inspect, JSON(JSON(t)).inspect
d = Date.today
assert_equal d, JSON(JSON(d))
d = DateTime.civil(2007, 6, 14, 14, 57, 10, Rational(1, 12), 2299161)
assert_equal d, JSON(JSON(d))
assert_equal 1..10, JSON(JSON(1..10))
assert_equal 1...10, JSON(JSON(1...10))
assert_equal "a".."c", JSON(JSON("a".."c"))
assert_equal "a"..."c", JSON(JSON("a"..."c"))
s = MyJsonStruct.new 4711, 'foot'
assert_equal s, JSON(JSON(s))
struct = Struct.new :foo, :bar
s = struct.new 4711, 'foot'
assert_raises(JSONError) { JSON(s) }
begin
raise TypeError, "test me"
rescue TypeError => e
e_json = JSON.generate e
e_again = JSON e_json
assert_kind_of TypeError, e_again
assert_equal e.message, e_again.message
assert_equal e.backtrace, e_again.backtrace
end
assert_equal(/foo/, JSON(JSON(/foo/)))
assert_equal(/foo/i, JSON(JSON(/foo/i)))
end
def test_utc_datetime
now = Time.now
d = DateTime.parse(now.to_s) # usual case
assert_equal d, JSON.parse(d.to_json)
d = DateTime.parse(now.utc.to_s) # of = 0
assert_equal d, JSON.parse(d.to_json)
d = DateTime.civil(2008, 6, 17, 11, 48, 32, Rational(1,24))
assert_equal d, JSON.parse(d.to_json)
d = DateTime.civil(2008, 6, 17, 11, 48, 32, Rational(12,24))
assert_equal d, JSON.parse(d.to_json)
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/gems/1.8/gems/json_pure-1.4.6/tests/test_json.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/tests/test_json.rb | #!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'test/unit'
case ENV['JSON']
when 'pure' then require 'json/pure'
when 'ext' then require 'json/ext'
else require 'json'
end
require 'stringio'
unless Array.method_defined?(:permutation)
begin
require 'enumerator'
require 'permutation'
class Array
def permutation
Permutation.for(self).to_enum.map { |x| x.project }
end
end
rescue LoadError
warn "Skipping permutation tests."
end
end
class TC_JSON < Test::Unit::TestCase
include JSON
def setup
@ary = [1, "foo", 3.14, 4711.0, 2.718, nil, [1,-2,3], false, true].map do
|x| [x]
end
@ary_to_parse = ["1", '"foo"', "3.14", "4711.0", "2.718", "null",
"[1,-2,3]", "false", "true"].map do
|x| "[#{x}]"
end
@hash = {
'a' => 2,
'b' => 3.141,
'c' => 'c',
'd' => [ 1, "b", 3.14 ],
'e' => { 'foo' => 'bar' },
'g' => "\"\0\037",
'h' => 1000.0,
'i' => 0.001
}
@json = '{"a":2,"b":3.141,"c":"c","d":[1,"b",3.14],"e":{"foo":"bar"},'\
'"g":"\\"\\u0000\\u001f","h":1.0E3,"i":1.0E-3}'
end
def test_construction
parser = JSON::Parser.new('test')
assert_equal 'test', parser.source
end
def assert_equal_float(expected, is)
assert_in_delta(expected.first, is.first, 1e-2)
end
def test_parse_simple_arrays
assert_equal([], parse('[]'))
assert_equal([], parse(' [ ] '))
assert_equal([nil], parse('[null]'))
assert_equal([false], parse('[false]'))
assert_equal([true], parse('[true]'))
assert_equal([-23], parse('[-23]'))
assert_equal([23], parse('[23]'))
assert_equal([0.23], parse('[0.23]'))
assert_equal([0.0], parse('[0e0]'))
assert_raises(JSON::ParserError) { parse('[+23.2]') }
assert_raises(JSON::ParserError) { parse('[+23]') }
assert_raises(JSON::ParserError) { parse('[.23]') }
assert_raises(JSON::ParserError) { parse('[023]') }
assert_equal_float [3.141], parse('[3.141]')
assert_equal_float [-3.141], parse('[-3.141]')
assert_equal_float [3.141], parse('[3141e-3]')
assert_equal_float [3.141], parse('[3141.1e-3]')
assert_equal_float [3.141], parse('[3141E-3]')
assert_equal_float [3.141], parse('[3141.0E-3]')
assert_equal_float [-3.141], parse('[-3141.0e-3]')
assert_equal_float [-3.141], parse('[-3141e-3]')
assert_raises(ParserError) { parse('[NaN]') }
assert parse('[NaN]', :allow_nan => true).first.nan?
assert_raises(ParserError) { parse('[Infinity]') }
assert_equal [1.0/0], parse('[Infinity]', :allow_nan => true)
assert_raises(ParserError) { parse('[-Infinity]') }
assert_equal [-1.0/0], parse('[-Infinity]', :allow_nan => true)
assert_equal([""], parse('[""]'))
assert_equal(["foobar"], parse('["foobar"]'))
assert_equal([{}], parse('[{}]'))
end
def test_parse_simple_objects
assert_equal({}, parse('{}'))
assert_equal({}, parse(' { } '))
assert_equal({ "a" => nil }, parse('{ "a" : null}'))
assert_equal({ "a" => nil }, parse('{"a":null}'))
assert_equal({ "a" => false }, parse('{ "a" : false } '))
assert_equal({ "a" => false }, parse('{"a":false}'))
assert_raises(JSON::ParserError) { parse('{false}') }
assert_equal({ "a" => true }, parse('{"a":true}'))
assert_equal({ "a" => true }, parse(' { "a" : true } '))
assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
assert_equal({ "a" => -23 }, parse(' { "a" : -23 } '))
assert_equal({ "a" => 23 }, parse('{"a":23 } '))
assert_equal({ "a" => 23 }, parse(' { "a" : 23 } '))
assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
assert_equal({ "a" => 0.23 }, parse(' { "a" : 0.23 } '))
end
if Array.method_defined?(:permutation)
def test_parse_more_complex_arrays
a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
a.permutation.each do |perm|
json = pretty_generate(perm)
assert_equal perm, parse(json)
end
end
def test_parse_complex_objects
a = [ nil, false, true, "foßbar", [ "n€st€d", true ], { "nested" => true, "n€ßt€ð2" => {} }]
a.permutation.each do |perm|
s = "a"
orig_obj = perm.inject({}) { |h, x| h[s.dup] = x; s = s.succ; h }
json = pretty_generate(orig_obj)
assert_equal orig_obj, parse(json)
end
end
end
def test_parse_arrays
assert_equal([1,2,3], parse('[1,2,3]'))
assert_equal([1.2,2,3], parse('[1.2,2,3]'))
assert_equal([[],[[],[]]], parse('[[],[[],[]]]'))
end
def test_parse_values
assert_equal([""], parse('[""]'))
assert_equal(["\\"], parse('["\\\\"]'))
assert_equal(['"'], parse('["\""]'))
assert_equal(['\\"\\'], parse('["\\\\\\"\\\\"]'))
assert_equal(["\"\b\n\r\t\0\037"],
parse('["\"\b\n\r\t\u0000\u001f"]'))
for i in 0 ... @ary.size
assert_equal(@ary[i], parse(@ary_to_parse[i]))
end
end
def test_parse_array
assert_equal([], parse('[]'))
assert_equal([], parse(' [ ] '))
assert_equal([1], parse('[1]'))
assert_equal([1], parse(' [ 1 ] '))
assert_equal(@ary,
parse('[[1],["foo"],[3.14],[47.11e+2],[2718.0E-3],[null],[[1,-2,3]]'\
',[false],[true]]'))
assert_equal(@ary, parse(%Q{ [ [1] , ["foo"] , [3.14] \t , [47.11e+2]
, [2718.0E-3 ],\r[ null] , [[1, -2, 3 ]], [false ],[ true]\n ] }))
end
class SubArray < Array; end
class SubArray2 < Array
def to_json(*a)
{
JSON.create_id => self.class.name,
'ary' => to_a,
}.to_json(*a)
end
def self.json_create(o)
o.delete JSON.create_id
o['ary']
end
end
def test_parse_array_custom_class
res = parse('[]', :array_class => SubArray)
assert_equal([], res)
assert_equal(SubArray, res.class)
end
def test_parse_object
assert_equal({}, parse('{}'))
assert_equal({}, parse(' { } '))
assert_equal({'foo'=>'bar'}, parse('{"foo":"bar"}'))
assert_equal({'foo'=>'bar'}, parse(' { "foo" : "bar" } '))
end
class SubHash < Hash
end
class SubHash2 < Hash
def to_json(*a)
{
JSON.create_id => self.class.name,
}.merge(self).to_json(*a)
end
def self.json_create(o)
o.delete JSON.create_id
self[o]
end
end
def test_parse_object_custom_class
res = parse('{}', :object_class => SubHash2)
assert_equal({}, res)
assert_equal(SubHash2, res.class)
end
def test_generation_of_core_subclasses_with_new_to_json
obj = SubHash2["foo" => SubHash2["bar" => true]]
obj_json = JSON(obj)
obj_again = JSON(obj_json)
assert_kind_of SubHash2, obj_again
assert_kind_of SubHash2, obj_again['foo']
assert obj_again['foo']['bar']
assert_equal obj, obj_again
assert_equal ["foo"], JSON(JSON(SubArray2["foo"]))
end
def test_generation_of_core_subclasses_with_default_to_json
assert_equal '{"foo":"bar"}', JSON(SubHash["foo" => "bar"])
assert_equal '["foo"]', JSON(SubArray["foo"])
end
def test_generation_of_core_subclasses
obj = SubHash["foo" => SubHash["bar" => true]]
obj_json = JSON(obj)
obj_again = JSON(obj_json)
assert_kind_of Hash, obj_again
assert_kind_of Hash, obj_again['foo']
assert obj_again['foo']['bar']
assert_equal obj, obj_again
end
def test_parser_reset
parser = Parser.new(@json)
assert_equal(@hash, parser.parse)
assert_equal(@hash, parser.parse)
end
def test_comments
json = <<EOT
{
"key1":"value1", // eol comment
"key2":"value2" /* multi line
* comment */,
"key3":"value3" /* multi line
// nested eol comment
* comment */
}
EOT
assert_equal(
{ "key1" => "value1", "key2" => "value2", "key3" => "value3" },
parse(json))
json = <<EOT
{
"key1":"value1" /* multi line
// nested eol comment
/* illegal nested multi line comment */
* comment */
}
EOT
assert_raises(ParserError) { parse(json) }
json = <<EOT
{
"key1":"value1" /* multi line
// nested eol comment
closed multi comment */
and again, throw an Error */
}
EOT
assert_raises(ParserError) { parse(json) }
json = <<EOT
{
"key1":"value1" /*/*/
}
EOT
assert_equal({ "key1" => "value1" }, parse(json))
end
def test_backslash
data = [ '\\.(?i:gif|jpe?g|png)$' ]
json = '["\\\\.(?i:gif|jpe?g|png)$"]'
assert_equal json, JSON.generate(data)
assert_equal data, JSON.parse(json)
#
data = [ '\\"' ]
json = '["\\\\\""]'
assert_equal json, JSON.generate(data)
assert_equal data, JSON.parse(json)
#
json = '["/"]'
data = JSON.parse(json)
assert_equal ['/'], data
assert_equal json, JSON.generate(data)
#
json = '["\""]'
data = JSON.parse(json)
assert_equal ['"'], data
assert_equal json, JSON.generate(data)
json = '["\\\'"]'
data = JSON.parse(json)
assert_equal ["'"], data
assert_equal '["\'"]', JSON.generate(data)
end
def test_wrong_inputs
assert_raises(ParserError) { JSON.parse('"foo"') }
assert_raises(ParserError) { JSON.parse('123') }
assert_raises(ParserError) { JSON.parse('[] bla') }
assert_raises(ParserError) { JSON.parse('[] 1') }
assert_raises(ParserError) { JSON.parse('[] []') }
assert_raises(ParserError) { JSON.parse('[] {}') }
assert_raises(ParserError) { JSON.parse('{} []') }
assert_raises(ParserError) { JSON.parse('{} {}') }
assert_raises(ParserError) { JSON.parse('[NULL]') }
assert_raises(ParserError) { JSON.parse('[FALSE]') }
assert_raises(ParserError) { JSON.parse('[TRUE]') }
assert_raises(ParserError) { JSON.parse('[07] ') }
assert_raises(ParserError) { JSON.parse('[0a]') }
assert_raises(ParserError) { JSON.parse('[1.]') }
assert_raises(ParserError) { JSON.parse(' ') }
end
def test_nesting
assert_raises(JSON::NestingError) { JSON.parse '[[]]', :max_nesting => 1 }
assert_raises(JSON::NestingError) { JSON.parser.new('[[]]', :max_nesting => 1).parse }
assert_equal [[]], JSON.parse('[[]]', :max_nesting => 2)
too_deep = '[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]'
too_deep_ary = eval too_deep
assert_raises(JSON::NestingError) { JSON.parse too_deep }
assert_raises(JSON::NestingError) { JSON.parser.new(too_deep).parse }
assert_raises(JSON::NestingError) { JSON.parse too_deep, :max_nesting => 19 }
ok = JSON.parse too_deep, :max_nesting => 20
assert_equal too_deep_ary, ok
ok = JSON.parse too_deep, :max_nesting => nil
assert_equal too_deep_ary, ok
ok = JSON.parse too_deep, :max_nesting => false
assert_equal too_deep_ary, ok
ok = JSON.parse too_deep, :max_nesting => 0
assert_equal too_deep_ary, ok
assert_raises(JSON::NestingError) { JSON.generate [[]], :max_nesting => 1 }
assert_equal '[[]]', JSON.generate([[]], :max_nesting => 2)
assert_raises(JSON::NestingError) { JSON.generate too_deep_ary }
assert_raises(JSON::NestingError) { JSON.generate too_deep_ary, :max_nesting => 19 }
ok = JSON.generate too_deep_ary, :max_nesting => 20
assert_equal too_deep, ok
ok = JSON.generate too_deep_ary, :max_nesting => nil
assert_equal too_deep, ok
ok = JSON.generate too_deep_ary, :max_nesting => false
assert_equal too_deep, ok
ok = JSON.generate too_deep_ary, :max_nesting => 0
assert_equal too_deep, ok
end
def test_symbolize_names
assert_equal({ "foo" => "bar", "baz" => "quux" },
JSON.parse('{"foo":"bar", "baz":"quux"}'))
assert_equal({ :foo => "bar", :baz => "quux" },
JSON.parse('{"foo":"bar", "baz":"quux"}', :symbolize_names => true))
end
def test_load_dump
too_deep = '[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]'
assert_equal too_deep, JSON.dump(eval(too_deep))
assert_kind_of String, Marshal.dump(eval(too_deep))
assert_raises(ArgumentError) { JSON.dump(eval(too_deep), 19) }
assert_raises(ArgumentError) { Marshal.dump(eval(too_deep), 19) }
assert_equal too_deep, JSON.dump(eval(too_deep), 20)
assert_kind_of String, Marshal.dump(eval(too_deep), 20)
output = StringIO.new
JSON.dump(eval(too_deep), output)
assert_equal too_deep, output.string
output = StringIO.new
JSON.dump(eval(too_deep), output, 20)
assert_equal too_deep, output.string
end
def test_big_integers
json1 = JSON([orig = (1 << 31) - 1])
assert_equal orig, JSON[json1][0]
json2 = JSON([orig = 1 << 31])
assert_equal orig, JSON[json2][0]
json3 = JSON([orig = (1 << 62) - 1])
assert_equal orig, JSON[json3][0]
json4 = JSON([orig = 1 << 62])
assert_equal orig, JSON[json4][0]
json5 = JSON([orig = 1 << 64])
assert_equal orig, JSON[json5][0]
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/gems/1.8/gems/json_pure-1.4.6/bin/prettify_json.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/bin/prettify_json.rb | #!/usr/bin/env ruby
require 'json'
require 'fileutils'
include FileUtils
# Parses the argument array _args_, according to the pattern _s_, to
# retrieve the single character command line options from it. If _s_ is
# 'xy:' an option '-x' without an option argument is searched, and an
# option '-y foo' with an option argument ('foo').
#
# An option hash is returned with all found options set to true or the
# found option argument.
def go(s, args = ARGV)
b, v = s.scan(/(.)(:?)/).inject([{},{}]) { |t,(o,a)|
t[a.empty? ? 0 : 1][o] = a.empty? ? false : nil
t
}
while a = args.shift
a !~ /\A-(.+)/ and args.unshift a and break
p = $1
until p == ''
o = p.slice!(0, 1)
if v.key?(o)
v[o] = if p == '' then args.shift or break 1 else p end
break
elsif b.key?(o)
b[o] = true
else
args.unshift a
break 1
end
end and break
end
b.merge(v)
end
opts = go 'slhi:', args = ARGV.dup
if opts['h'] || opts['l'] && opts['s']
puts <<EOT
Usage: #{File.basename($0)} [OPTION] [FILE]
If FILE is skipped, this scripts waits for input from STDIN. Otherwise
FILE is opened, read, and used as input for the prettifier.
OPTION can be
-s to output the shortest possible JSON (precludes -l)
-l to output a longer, better formatted JSON (precludes -s)
-i EXT prettifies FILE in place, saving a backup to FILE.EXT
-h this help
EOT
exit 0
end
filename = nil
json = JSON[
if args.empty?
STDIN.read
else
File.read filename = args.first
end
]
output = if opts['s']
JSON.fast_generate json
else # default is -l
JSON.pretty_generate json
end
if opts['i'] && filename
cp filename, "#{filename}.#{opts['i']}"
File.open(filename, 'w') { |f| f.puts output }
else
puts output
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/gems/1.8/gems/json_pure-1.4.6/bin/edit_json.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/bin/edit_json.rb | #!/usr/bin/env ruby
require 'json/editor'
filename, encoding = ARGV
JSON::Editor.start(encoding) do |window|
if filename
window.file_open(filename)
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/gems/1.8/gems/json_pure-1.4.6/ext/json/ext/generator/extconf.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/ext/json/ext/generator/extconf.rb | require 'mkmf'
require 'rbconfig'
unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O3')
$CFLAGS << ' -O3'
end
if CONFIG['CC'] =~ /gcc/
$CFLAGS << ' -Wall'
#unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O0 -ggdb')
# $CFLAGS << ' -O0 -ggdb'
#end
end
if RUBY_VERSION < "1.9"
have_header("re.h")
else
have_header("ruby/re.h")
have_header("ruby/encoding.h")
end
create_makefile 'json/ext/generator'
| 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/gems/1.8/gems/json_pure-1.4.6/ext/json/ext/parser/extconf.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/ext/json/ext/parser/extconf.rb | require 'mkmf'
require 'rbconfig'
unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O3')
$CFLAGS << ' -O3'
end
if CONFIG['CC'] =~ /gcc/
$CFLAGS << ' -Wall'
#unless $CFLAGS.gsub!(/ -O[\dsz]?/, ' -O0 -ggdb')
# $CFLAGS << ' -O0 -ggdb'
#end
end
have_header("re.h")
create_makefile 'json/ext/parser'
| 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/gems/1.8/gems/json_pure-1.4.6/lib/json.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json.rb | require 'json/common'
module JSON
require 'json/version'
begin
require 'json/ext'
rescue LoadError
require 'json/pure'
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/gems/1.8/gems/json_pure-1.4.6/lib/json/common.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/common.rb | require 'json/version'
require 'iconv'
module JSON
class << self
# If _object_ is string-like parse the string and return the parsed result
# as a Ruby data structure. Otherwise generate a JSON text from the Ruby
# data structure object and return it.
#
# The _opts_ argument is passed through to generate/parse respectively, see
# generate and parse for their documentation.
def [](object, opts = {})
if object.respond_to? :to_str
JSON.parse(object.to_str, opts)
else
JSON.generate(object, opts)
end
end
# Returns the JSON parser class, that is used by JSON. This might be either
# JSON::Ext::Parser or JSON::Pure::Parser.
attr_reader :parser
# Set the JSON parser class _parser_ to be used by JSON.
def parser=(parser) # :nodoc:
@parser = parser
remove_const :Parser if const_defined? :Parser
const_set :Parser, parser
end
# Return the constant located at _path_. The format of _path_ has to be
# either ::A::B::C or A::B::C. In any case A has to be located at the top
# level (absolute namespace path?). If there doesn't exist a constant at
# the given path, an ArgumentError is raised.
def deep_const_get(path) # :nodoc:
path.to_s.split(/::/).inject(Object) do |p, c|
case
when c.empty? then p
when p.const_defined?(c) then p.const_get(c)
else
begin
p.const_missing(c)
rescue NameError
raise ArgumentError, "can't find const #{path}"
end
end
end
end
# Set the module _generator_ to be used by JSON.
def generator=(generator) # :nodoc:
@generator = generator
generator_methods = generator::GeneratorMethods
for const in generator_methods.constants
klass = deep_const_get(const)
modul = generator_methods.const_get(const)
klass.class_eval do
instance_methods(false).each do |m|
m.to_s == 'to_json' and remove_method m
end
include modul
end
end
self.state = generator::State
const_set :State, self.state
const_set :SAFE_STATE_PROTOTYPE, State.new
const_set :FAST_STATE_PROTOTYPE, State.new(
:indent => '',
:space => '',
:object_nl => "",
:array_nl => "",
:max_nesting => false
)
const_set :PRETTY_STATE_PROTOTYPE, State.new(
:indent => ' ',
:space => ' ',
:object_nl => "\n",
:array_nl => "\n"
)
end
# Returns the JSON generator modul, that is used by JSON. This might be
# either JSON::Ext::Generator or JSON::Pure::Generator.
attr_reader :generator
# Returns the JSON generator state class, that is used by JSON. This might
# be either JSON::Ext::Generator::State or JSON::Pure::Generator::State.
attr_accessor :state
# This is create identifier, that is used to decide, if the _json_create_
# hook of a class should be called. It defaults to 'json_class'.
attr_accessor :create_id
end
self.create_id = 'json_class'
NaN = 0.0/0
Infinity = 1.0/0
MinusInfinity = -Infinity
# The base exception for JSON errors.
class JSONError < StandardError; end
# This exception is raised, if a parser error occurs.
class ParserError < JSONError; end
# This exception is raised, if the nesting of parsed datastructures is too
# deep.
class NestingError < ParserError; end
# :stopdoc:
class CircularDatastructure < NestingError; end
# :startdoc:
# This exception is raised, if a generator or unparser error occurs.
class GeneratorError < JSONError; end
# For backwards compatibility
UnparserError = GeneratorError
# This exception is raised, if the required unicode support is missing on the
# system. Usually this means, that the iconv library is not installed.
class MissingUnicodeSupport < JSONError; end
module_function
# Parse the JSON document _source_ into a Ruby data structure and return it.
#
# _opts_ can have the following
# keys:
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
# structures. Disable depth checking with :max_nesting => false, it defaults
# to 19.
# * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
# to false.
# * *symbolize_names*: If set to true, returns symbols for the names
# (keys) in a JSON object. Otherwise strings are returned, which is also
# the default.
# * *create_additions*: If set to false, the Parser doesn't create
# additions even if a matchin class and create_id was found. This option
# defaults to true.
# * *object_class*: Defaults to Hash
# * *array_class*: Defaults to Array
def parse(source, opts = {})
Parser.new(source, opts).parse
end
# Parse the JSON document _source_ into a Ruby data structure and return it.
# The bang version of the parse method, defaults to the more dangerous values
# for the _opts_ hash, so be sure only to parse trusted _source_ documents.
#
# _opts_ can have the following keys:
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
# structures. Enable depth checking with :max_nesting => anInteger. The parse!
# methods defaults to not doing max depth checking: This can be dangerous,
# if someone wants to fill up your stack.
# * *allow_nan*: If set to true, allow NaN, Infinity, and -Infinity in
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
# to true.
# * *create_additions*: If set to false, the Parser doesn't create
# additions even if a matchin class and create_id was found. This option
# defaults to true.
def parse!(source, opts = {})
opts = {
:max_nesting => false,
:allow_nan => true
}.update(opts)
Parser.new(source, opts).parse
end
# Generate a JSON document from the Ruby data structure _obj_ and return
# it. _state_ is * a JSON::State object,
# * or a Hash like object (responding to to_hash),
# * an object convertible into a hash by a to_h method,
# that is used as or to configure a State object.
#
# It defaults to a state object, that creates the shortest possible JSON text
# in one line, checks for circular data structures and doesn't allow NaN,
# Infinity, and -Infinity.
#
# A _state_ hash can have the following keys:
# * *indent*: a string used to indent levels (default: ''),
# * *space*: a string that is put after, a : or , delimiter (default: ''),
# * *space_before*: a string that is put before a : pair delimiter (default: ''),
# * *object_nl*: a string that is put at the end of a JSON object (default: ''),
# * *array_nl*: a string that is put at the end of a JSON array (default: ''),
# * *allow_nan*: true if NaN, Infinity, and -Infinity should be
# generated, otherwise an exception is thrown, if these values are
# encountered. This options defaults to false.
# * *max_nesting*: The maximum depth of nesting allowed in the data
# structures from which JSON is to be generated. Disable depth checking
# with :max_nesting => false, it defaults to 19.
#
# See also the fast_generate for the fastest creation method with the least
# amount of sanity checks, and the pretty_generate method for some
# defaults for a pretty output.
def generate(obj, opts = nil)
state = SAFE_STATE_PROTOTYPE.dup
if opts
if opts.respond_to? :to_hash
opts = opts.to_hash
elsif opts.respond_to? :to_h
opts = opts.to_h
else
raise TypeError, "can't convert #{opts.class} into Hash"
end
state = state.configure(opts)
end
state.generate(obj)
end
# :stopdoc:
# I want to deprecate these later, so I'll first be silent about them, and
# later delete them.
alias unparse generate
module_function :unparse
# :startdoc:
# Generate a JSON document from the Ruby data structure _obj_ and return it.
# This method disables the checks for circles in Ruby objects.
#
# *WARNING*: Be careful not to pass any Ruby data structures with circles as
# _obj_ argument, because this will cause JSON to go into an infinite loop.
def fast_generate(obj, opts = nil)
state = FAST_STATE_PROTOTYPE.dup
if opts
if opts.respond_to? :to_hash
opts = opts.to_hash
elsif opts.respond_to? :to_h
opts = opts.to_h
else
raise TypeError, "can't convert #{opts.class} into Hash"
end
state.configure(opts)
end
state.generate(obj)
end
# :stopdoc:
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
alias fast_unparse fast_generate
module_function :fast_unparse
# :startdoc:
# Generate a JSON document from the Ruby data structure _obj_ and return it.
# The returned document is a prettier form of the document returned by
# #unparse.
#
# The _opts_ argument can be used to configure the generator, see the
# generate method for a more detailed explanation.
def pretty_generate(obj, opts = nil)
state = PRETTY_STATE_PROTOTYPE.dup
if opts
if opts.respond_to? :to_hash
opts = opts.to_hash
elsif opts.respond_to? :to_h
opts = opts.to_h
else
raise TypeError, "can't convert #{opts.class} into Hash"
end
state.configure(opts)
end
state.generate(obj)
end
# :stopdoc:
# I want to deprecate these later, so I'll first be silent about them, and later delete them.
alias pretty_unparse pretty_generate
module_function :pretty_unparse
# :startdoc:
# Load a ruby data structure from a JSON _source_ and return it. A source can
# either be a string-like object, an IO like object, or an object responding
# to the read method. If _proc_ was given, it will be called with any nested
# Ruby object as an argument recursively in depth first order.
#
# This method is part of the implementation of the load/dump interface of
# Marshal and YAML.
def load(source, proc = nil)
if source.respond_to? :to_str
source = source.to_str
elsif source.respond_to? :to_io
source = source.to_io.read
else
source = source.read
end
result = parse(source, :max_nesting => false, :allow_nan => true)
recurse_proc(result, &proc) if proc
result
end
def recurse_proc(result, &proc)
case result
when Array
result.each { |x| recurse_proc x, &proc }
proc.call result
when Hash
result.each { |x, y| recurse_proc x, &proc; recurse_proc y, &proc }
proc.call result
else
proc.call result
end
end
alias restore load
module_function :restore
# Dumps _obj_ as a JSON string, i.e. calls generate on the object and returns
# the result.
#
# If anIO (an IO like object or an object that responds to the write method)
# was given, the resulting JSON is written to it.
#
# If the number of nested arrays or objects exceeds _limit_ an ArgumentError
# exception is raised. This argument is similar (but not exactly the
# same!) to the _limit_ argument in Marshal.dump.
#
# This method is part of the implementation of the load/dump interface of
# Marshal and YAML.
def dump(obj, anIO = nil, limit = nil)
if anIO and limit.nil?
anIO = anIO.to_io if anIO.respond_to?(:to_io)
unless anIO.respond_to?(:write)
limit = anIO
anIO = nil
end
end
limit ||= 0
result = generate(obj, :allow_nan => true, :max_nesting => limit)
if anIO
anIO.write result
anIO
else
result
end
rescue JSON::NestingError
raise ArgumentError, "exceed depth limit"
end
# Shortuct for iconv.
def self.iconv(to, from, string)
Iconv.iconv(to, from, string).first
end
end
module ::Kernel
private
# Outputs _objs_ to STDOUT as JSON strings in the shortest form, that is in
# one line.
def j(*objs)
objs.each do |obj|
puts JSON::generate(obj, :allow_nan => true, :max_nesting => false)
end
nil
end
# Ouputs _objs_ to STDOUT as JSON strings in a pretty format, with
# indentation and over many lines.
def jj(*objs)
objs.each do |obj|
puts JSON::pretty_generate(obj, :allow_nan => true, :max_nesting => false)
end
nil
end
# If _object_ is string-like parse the string and return the parsed result as
# a Ruby data structure. Otherwise generate a JSON text from the Ruby data
# structure object and return it.
#
# The _opts_ argument is passed through to generate/parse respectively, see
# generate and parse for their documentation.
def JSON(object, *args)
if object.respond_to? :to_str
JSON.parse(object.to_str, args.first)
else
JSON.generate(object, args.first)
end
end
end
class ::Class
# Returns true, if this class can be used to create an instance
# from a serialised JSON string. The class has to implement a class
# method _json_create_ that expects a hash as first parameter, which includes
# the required data.
def json_creatable?
respond_to?(:json_create)
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/gems/1.8/gems/json_pure-1.4.6/lib/json/version.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/version.rb | module JSON
# JSON version
VERSION = '1.4.6'
VERSION_ARRAY = VERSION.split(/\./).map { |x| x.to_i } # :nodoc:
VERSION_MAJOR = VERSION_ARRAY[0] # :nodoc:
VERSION_MINOR = VERSION_ARRAY[1] # :nodoc:
VERSION_BUILD = VERSION_ARRAY[2] # :nodoc:
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/gems/1.8/gems/json_pure-1.4.6/lib/json/ext.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/ext.rb | require 'json/common'
module JSON
# This module holds all the modules/classes that implement JSON's
# functionality as C extensions.
module Ext
require 'json/ext/parser'
require 'json/ext/generator'
$DEBUG and warn "Using c extension for JSON."
JSON.parser = Parser
JSON.generator = Generator
end
JSON_LOADED = true
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/gems/1.8/gems/json_pure-1.4.6/lib/json/pure.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/pure.rb | require 'json/common'
require 'json/pure/parser'
require 'json/pure/generator'
module JSON
begin
require 'iconv'
# An iconv instance to convert from UTF8 to UTF16 Big Endian.
UTF16toUTF8 = Iconv.new('utf-8', 'utf-16be') # :nodoc:
# An iconv instance to convert from UTF16 Big Endian to UTF8.
UTF8toUTF16 = Iconv.new('utf-16be', 'utf-8') # :nodoc:
UTF8toUTF16.iconv('no bom')
rescue LoadError
raise MissingUnicodeSupport,
"iconv couldn't be loaded, which is required for UTF-8/UTF-16 conversions"
rescue Errno::EINVAL, Iconv::InvalidEncoding
# Iconv doesn't support big endian utf-16. Let's try to hack this manually
# into the converters.
begin
old_verbose, $VERBSOSE = $VERBOSE, nil
# An iconv instance to convert from UTF8 to UTF16 Big Endian.
UTF16toUTF8 = Iconv.new('utf-8', 'utf-16') # :nodoc:
# An iconv instance to convert from UTF16 Big Endian to UTF8.
UTF8toUTF16 = Iconv.new('utf-16', 'utf-8') # :nodoc:
UTF8toUTF16.iconv('no bom')
if UTF8toUTF16.iconv("\xe2\x82\xac") == "\xac\x20"
swapper = Class.new do
def initialize(iconv) # :nodoc:
@iconv = iconv
end
def iconv(string) # :nodoc:
result = @iconv.iconv(string)
JSON.swap!(result)
end
end
UTF8toUTF16 = swapper.new(UTF8toUTF16) # :nodoc:
end
if UTF16toUTF8.iconv("\xac\x20") == "\xe2\x82\xac"
swapper = Class.new do
def initialize(iconv) # :nodoc:
@iconv = iconv
end
def iconv(string) # :nodoc:
string = JSON.swap!(string.dup)
@iconv.iconv(string)
end
end
UTF16toUTF8 = swapper.new(UTF16toUTF8) # :nodoc:
end
rescue Errno::EINVAL, Iconv::InvalidEncoding
raise MissingUnicodeSupport, "iconv doesn't seem to support UTF-8/UTF-16 conversions"
ensure
$VERBOSE = old_verbose
end
end
# Swap consecutive bytes of _string_ in place.
def self.swap!(string) # :nodoc:
0.upto(string.size / 2) do |i|
break unless string[2 * i + 1]
string[2 * i], string[2 * i + 1] = string[2 * i + 1], string[2 * i]
end
string
end
# This module holds all the modules/classes that implement JSON's
# functionality in pure ruby.
module Pure
$DEBUG and warn "Using pure library for JSON."
JSON.parser = Parser
JSON.generator = Generator
end
JSON_LOADED = true
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/gems/1.8/gems/json_pure-1.4.6/lib/json/editor.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/editor.rb | # To use the GUI JSON editor, start the edit_json.rb executable script. It
# requires ruby-gtk to be installed.
require 'gtk2'
require 'iconv'
require 'json'
require 'rbconfig'
require 'open-uri'
module JSON
module Editor
include Gtk
# Beginning of the editor window title
TITLE = 'JSON Editor'.freeze
# Columns constants
ICON_COL, TYPE_COL, CONTENT_COL = 0, 1, 2
# JSON primitive types (Containers)
CONTAINER_TYPES = %w[Array Hash].sort
# All JSON primitive types
ALL_TYPES = (%w[TrueClass FalseClass Numeric String NilClass] +
CONTAINER_TYPES).sort
# The Nodes necessary for the tree representation of a JSON document
ALL_NODES = (ALL_TYPES + %w[Key]).sort
DEFAULT_DIALOG_KEY_PRESS_HANDLER = lambda do |dialog, event|
case event.keyval
when Gdk::Keyval::GDK_Return
dialog.response Dialog::RESPONSE_ACCEPT
when Gdk::Keyval::GDK_Escape
dialog.response Dialog::RESPONSE_REJECT
end
end
# Returns the Gdk::Pixbuf of the icon named _name_ from the icon cache.
def Editor.fetch_icon(name)
@icon_cache ||= {}
unless @icon_cache.key?(name)
path = File.dirname(__FILE__)
@icon_cache[name] = Gdk::Pixbuf.new(File.join(path, name + '.xpm'))
end
@icon_cache[name]
end
# Opens an error dialog on top of _window_ showing the error message
# _text_.
def Editor.error_dialog(window, text)
dialog = MessageDialog.new(window, Dialog::MODAL,
MessageDialog::ERROR,
MessageDialog::BUTTONS_CLOSE, text)
dialog.show_all
dialog.run
rescue TypeError
dialog = MessageDialog.new(Editor.window, Dialog::MODAL,
MessageDialog::ERROR,
MessageDialog::BUTTONS_CLOSE, text)
dialog.show_all
dialog.run
ensure
dialog.destroy if dialog
end
# Opens a yes/no question dialog on top of _window_ showing the error
# message _text_. If yes was answered _true_ is returned, otherwise
# _false_.
def Editor.question_dialog(window, text)
dialog = MessageDialog.new(window, Dialog::MODAL,
MessageDialog::QUESTION,
MessageDialog::BUTTONS_YES_NO, text)
dialog.show_all
dialog.run do |response|
return Gtk::Dialog::RESPONSE_YES === response
end
ensure
dialog.destroy if dialog
end
# Convert the tree model starting from Gtk::TreeIter _iter_ into a Ruby
# data structure and return it.
def Editor.model2data(iter)
return nil if iter.nil?
case iter.type
when 'Hash'
hash = {}
iter.each { |c| hash[c.content] = Editor.model2data(c.first_child) }
hash
when 'Array'
array = Array.new(iter.n_children)
iter.each_with_index { |c, i| array[i] = Editor.model2data(c) }
array
when 'Key'
iter.content
when 'String'
iter.content
when 'Numeric'
content = iter.content
if /\./.match(content)
content.to_f
else
content.to_i
end
when 'TrueClass'
true
when 'FalseClass'
false
when 'NilClass'
nil
else
fail "Unknown type found in model: #{iter.type}"
end
end
# Convert the Ruby data structure _data_ into tree model data for Gtk and
# returns the whole model. If the parameter _model_ wasn't given a new
# Gtk::TreeStore is created as the model. The _parent_ parameter specifies
# the parent node (iter, Gtk:TreeIter instance) to which the data is
# appended, alternativeley the result of the yielded block is used as iter.
def Editor.data2model(data, model = nil, parent = nil)
model ||= TreeStore.new(Gdk::Pixbuf, String, String)
iter = if block_given?
yield model
else
model.append(parent)
end
case data
when Hash
iter.type = 'Hash'
data.sort.each do |key, value|
pair_iter = model.append(iter)
pair_iter.type = 'Key'
pair_iter.content = key.to_s
Editor.data2model(value, model, pair_iter)
end
when Array
iter.type = 'Array'
data.each do |value|
Editor.data2model(value, model, iter)
end
when Numeric
iter.type = 'Numeric'
iter.content = data.to_s
when String, true, false, nil
iter.type = data.class.name
iter.content = data.nil? ? 'null' : data.to_s
else
iter.type = 'String'
iter.content = data.to_s
end
model
end
# The Gtk::TreeIter class is reopened and some auxiliary methods are added.
class Gtk::TreeIter
include Enumerable
# Traverse each of this Gtk::TreeIter instance's children
# and yield to them.
def each
n_children.times { |i| yield nth_child(i) }
end
# Recursively traverse all nodes of this Gtk::TreeIter's subtree
# (including self) and yield to them.
def recursive_each(&block)
yield self
each do |i|
i.recursive_each(&block)
end
end
# Remove the subtree of this Gtk::TreeIter instance from the
# model _model_.
def remove_subtree(model)
while current = first_child
model.remove(current)
end
end
# Returns the type of this node.
def type
self[TYPE_COL]
end
# Sets the type of this node to _value_. This implies setting
# the respective icon accordingly.
def type=(value)
self[TYPE_COL] = value
self[ICON_COL] = Editor.fetch_icon(value)
end
# Returns the content of this node.
def content
self[CONTENT_COL]
end
# Sets the content of this node to _value_.
def content=(value)
self[CONTENT_COL] = value
end
end
# This module bundles some method, that can be used to create a menu. It
# should be included into the class in question.
module MenuExtension
include Gtk
# Creates a Menu, that includes MenuExtension. _treeview_ is the
# Gtk::TreeView, on which it operates.
def initialize(treeview)
@treeview = treeview
@menu = Menu.new
end
# Returns the Gtk::TreeView of this menu.
attr_reader :treeview
# Returns the menu.
attr_reader :menu
# Adds a Gtk::SeparatorMenuItem to this instance's #menu.
def add_separator
menu.append SeparatorMenuItem.new
end
# Adds a Gtk::MenuItem to this instance's #menu. _label_ is the label
# string, _klass_ is the item type, and _callback_ is the procedure, that
# is called if the _item_ is activated.
def add_item(label, keyval = nil, klass = MenuItem, &callback)
label = "#{label} (C-#{keyval.chr})" if keyval
item = klass.new(label)
item.signal_connect(:activate, &callback)
if keyval
self.signal_connect(:'key-press-event') do |item, event|
if event.state & Gdk::Window::ModifierType::CONTROL_MASK != 0 and
event.keyval == keyval
callback.call item
end
end
end
menu.append item
item
end
# This method should be implemented in subclasses to create the #menu of
# this instance. It has to be called after an instance of this class is
# created, to build the menu.
def create
raise NotImplementedError
end
def method_missing(*a, &b)
treeview.__send__(*a, &b)
end
end
# This class creates the popup menu, that opens when clicking onto the
# treeview.
class PopUpMenu
include MenuExtension
# Change the type or content of the selected node.
def change_node(item)
if current = selection.selected
parent = current.parent
old_type, old_content = current.type, current.content
if ALL_TYPES.include?(old_type)
@clipboard_data = Editor.model2data(current)
type, content = ask_for_element(parent, current.type,
current.content)
if type
current.type, current.content = type, content
current.remove_subtree(model)
toplevel.display_status("Changed a node in tree.")
window.change
end
else
toplevel.display_status(
"Cannot change node of type #{old_type} in tree!")
end
end
end
# Cut the selected node and its subtree, and save it into the
# clipboard.
def cut_node(item)
if current = selection.selected
if current and current.type == 'Key'
@clipboard_data = {
current.content => Editor.model2data(current.first_child)
}
else
@clipboard_data = Editor.model2data(current)
end
model.remove(current)
window.change
toplevel.display_status("Cut a node from tree.")
end
end
# Copy the selected node and its subtree, and save it into the
# clipboard.
def copy_node(item)
if current = selection.selected
if current and current.type == 'Key'
@clipboard_data = {
current.content => Editor.model2data(current.first_child)
}
else
@clipboard_data = Editor.model2data(current)
end
window.change
toplevel.display_status("Copied a node from tree.")
end
end
# Paste the data in the clipboard into the selected Array or Hash by
# appending it.
def paste_node_appending(item)
if current = selection.selected
if @clipboard_data
case current.type
when 'Array'
Editor.data2model(@clipboard_data, model, current)
expand_collapse(current)
when 'Hash'
if @clipboard_data.is_a? Hash
parent = current.parent
hash = Editor.model2data(current)
model.remove(current)
hash.update(@clipboard_data)
Editor.data2model(hash, model, parent)
if parent
expand_collapse(parent)
elsif @expanded
expand_all
end
window.change
else
toplevel.display_status(
"Cannot paste non-#{current.type} data into '#{current.type}'!")
end
else
toplevel.display_status(
"Cannot paste node below '#{current.type}'!")
end
else
toplevel.display_status("Nothing to paste in clipboard!")
end
else
toplevel.display_status("Append a node into the root first!")
end
end
# Paste the data in the clipboard into the selected Array inserting it
# before the selected element.
def paste_node_inserting_before(item)
if current = selection.selected
if @clipboard_data
parent = current.parent or return
parent_type = parent.type
if parent_type == 'Array'
selected_index = parent.each_with_index do |c, i|
break i if c == current
end
Editor.data2model(@clipboard_data, model, parent) do |m|
m.insert_before(parent, current)
end
expand_collapse(current)
toplevel.display_status("Inserted an element to " +
"'#{parent_type}' before index #{selected_index}.")
window.change
else
toplevel.display_status(
"Cannot insert node below '#{parent_type}'!")
end
else
toplevel.display_status("Nothing to paste in clipboard!")
end
else
toplevel.display_status("Append a node into the root first!")
end
end
# Append a new node to the selected Hash or Array.
def append_new_node(item)
if parent = selection.selected
parent_type = parent.type
case parent_type
when 'Hash'
key, type, content = ask_for_hash_pair(parent)
key or return
iter = create_node(parent, 'Key', key)
iter = create_node(iter, type, content)
toplevel.display_status(
"Added a (key, value)-pair to '#{parent_type}'.")
window.change
when 'Array'
type, content = ask_for_element(parent)
type or return
iter = create_node(parent, type, content)
window.change
toplevel.display_status("Appendend an element to '#{parent_type}'.")
else
toplevel.display_status("Cannot append to '#{parent_type}'!")
end
else
type, content = ask_for_element
type or return
iter = create_node(nil, type, content)
window.change
end
end
# Insert a new node into an Array before the selected element.
def insert_new_node(item)
if current = selection.selected
parent = current.parent or return
parent_parent = parent.parent
parent_type = parent.type
if parent_type == 'Array'
selected_index = parent.each_with_index do |c, i|
break i if c == current
end
type, content = ask_for_element(parent)
type or return
iter = model.insert_before(parent, current)
iter.type, iter.content = type, content
toplevel.display_status("Inserted an element to " +
"'#{parent_type}' before index #{selected_index}.")
window.change
else
toplevel.display_status(
"Cannot insert node below '#{parent_type}'!")
end
else
toplevel.display_status("Append a node into the root first!")
end
end
# Recursively collapse/expand a subtree starting from the selected node.
def collapse_expand(item)
if current = selection.selected
if row_expanded?(current.path)
collapse_row(current.path)
else
expand_row(current.path, true)
end
else
toplevel.display_status("Append a node into the root first!")
end
end
# Create the menu.
def create
add_item("Change node", ?n, &method(:change_node))
add_separator
add_item("Cut node", ?X, &method(:cut_node))
add_item("Copy node", ?C, &method(:copy_node))
add_item("Paste node (appending)", ?A, &method(:paste_node_appending))
add_item("Paste node (inserting before)", ?I,
&method(:paste_node_inserting_before))
add_separator
add_item("Append new node", ?a, &method(:append_new_node))
add_item("Insert new node before", ?i, &method(:insert_new_node))
add_separator
add_item("Collapse/Expand node (recursively)", ?e,
&method(:collapse_expand))
menu.show_all
signal_connect(:button_press_event) do |widget, event|
if event.kind_of? Gdk::EventButton and event.button == 3
menu.popup(nil, nil, event.button, event.time)
end
end
signal_connect(:popup_menu) do
menu.popup(nil, nil, 0, Gdk::Event::CURRENT_TIME)
end
end
end
# This class creates the File pulldown menu.
class FileMenu
include MenuExtension
# Clear the model and filename, but ask to save the JSON document, if
# unsaved changes have occured.
def new(item)
window.clear
end
# Open a file and load it into the editor. Ask to save the JSON document
# first, if unsaved changes have occured.
def open(item)
window.file_open
end
def open_location(item)
window.location_open
end
# Revert the current JSON document in the editor to the saved version.
def revert(item)
window.instance_eval do
@filename and file_open(@filename)
end
end
# Save the current JSON document.
def save(item)
window.file_save
end
# Save the current JSON document under the given filename.
def save_as(item)
window.file_save_as
end
# Quit the editor, after asking to save any unsaved changes first.
def quit(item)
window.quit
end
# Create the menu.
def create
title = MenuItem.new('File')
title.submenu = menu
add_item('New', &method(:new))
add_item('Open', ?o, &method(:open))
add_item('Open location', ?l, &method(:open_location))
add_item('Revert', &method(:revert))
add_separator
add_item('Save', ?s, &method(:save))
add_item('Save As', ?S, &method(:save_as))
add_separator
add_item('Quit', ?q, &method(:quit))
title
end
end
# This class creates the Edit pulldown menu.
class EditMenu
include MenuExtension
# Copy data from model into primary clipboard.
def copy(item)
data = Editor.model2data(model.iter_first)
json = JSON.pretty_generate(data, :max_nesting => false)
c = Gtk::Clipboard.get(Gdk::Selection::PRIMARY)
c.text = json
end
# Copy json text from primary clipboard into model.
def paste(item)
c = Gtk::Clipboard.get(Gdk::Selection::PRIMARY)
if json = c.wait_for_text
window.ask_save if @changed
begin
window.edit json
rescue JSON::ParserError
window.clear
end
end
end
# Find a string in all nodes' contents and select the found node in the
# treeview.
def find(item)
@search = ask_for_find_term(@search) or return
iter = model.get_iter('0') or return
iter.recursive_each do |i|
if @iter
if @iter != i
next
else
@iter = nil
next
end
elsif @search.match(i[CONTENT_COL])
set_cursor(i.path, nil, false)
@iter = i
break
end
end
end
# Repeat the last search given by #find.
def find_again(item)
@search or return
iter = model.get_iter('0')
iter.recursive_each do |i|
if @iter
if @iter != i
next
else
@iter = nil
next
end
elsif @search.match(i[CONTENT_COL])
set_cursor(i.path, nil, false)
@iter = i
break
end
end
end
# Sort (Reverse sort) all elements of the selected array by the given
# expression. _x_ is the element in question.
def sort(item)
if current = selection.selected
if current.type == 'Array'
parent = current.parent
ary = Editor.model2data(current)
order, reverse = ask_for_order
order or return
begin
block = eval "lambda { |x| #{order} }"
if reverse
ary.sort! { |a,b| block[b] <=> block[a] }
else
ary.sort! { |a,b| block[a] <=> block[b] }
end
rescue => e
Editor.error_dialog(self, "Failed to sort Array with #{order}: #{e}!")
else
Editor.data2model(ary, model, parent) do |m|
m.insert_before(parent, current)
end
model.remove(current)
expand_collapse(parent)
window.change
toplevel.display_status("Array has been sorted.")
end
else
toplevel.display_status("Only Array nodes can be sorted!")
end
else
toplevel.display_status("Select an Array to sort first!")
end
end
# Create the menu.
def create
title = MenuItem.new('Edit')
title.submenu = menu
add_item('Copy', ?c, &method(:copy))
add_item('Paste', ?v, &method(:paste))
add_separator
add_item('Find', ?f, &method(:find))
add_item('Find Again', ?g, &method(:find_again))
add_separator
add_item('Sort', ?S, &method(:sort))
title
end
end
class OptionsMenu
include MenuExtension
# Collapse/Expand all nodes by default.
def collapsed_nodes(item)
if expanded
self.expanded = false
collapse_all
else
self.expanded = true
expand_all
end
end
# Toggle pretty saving mode on/off.
def pretty_saving(item)
@pretty_item.toggled
window.change
end
attr_reader :pretty_item
# Create the menu.
def create
title = MenuItem.new('Options')
title.submenu = menu
add_item('Collapsed nodes', nil, CheckMenuItem, &method(:collapsed_nodes))
@pretty_item = add_item('Pretty saving', nil, CheckMenuItem,
&method(:pretty_saving))
@pretty_item.active = true
window.unchange
title
end
end
# This class inherits from Gtk::TreeView, to configure it and to add a lot
# of behaviour to it.
class JSONTreeView < Gtk::TreeView
include Gtk
# Creates a JSONTreeView instance, the parameter _window_ is
# a MainWindow instance and used for self delegation.
def initialize(window)
@window = window
super(TreeStore.new(Gdk::Pixbuf, String, String))
self.selection.mode = SELECTION_BROWSE
@expanded = false
self.headers_visible = false
add_columns
add_popup_menu
end
# Returns the MainWindow instance of this JSONTreeView.
attr_reader :window
# Returns true, if nodes are autoexpanding, false otherwise.
attr_accessor :expanded
private
def add_columns
cell = CellRendererPixbuf.new
column = TreeViewColumn.new('Icon', cell,
'pixbuf' => ICON_COL
)
append_column(column)
cell = CellRendererText.new
column = TreeViewColumn.new('Type', cell,
'text' => TYPE_COL
)
append_column(column)
cell = CellRendererText.new
cell.editable = true
column = TreeViewColumn.new('Content', cell,
'text' => CONTENT_COL
)
cell.signal_connect(:edited, &method(:cell_edited))
append_column(column)
end
def unify_key(iter, key)
return unless iter.type == 'Key'
parent = iter.parent
if parent.any? { |c| c != iter and c.content == key }
old_key = key
i = 0
begin
key = sprintf("%s.%d", old_key, i += 1)
end while parent.any? { |c| c != iter and c.content == key }
end
iter.content = key
end
def cell_edited(cell, path, value)
iter = model.get_iter(path)
case iter.type
when 'Key'
unify_key(iter, value)
toplevel.display_status('Key has been changed.')
when 'FalseClass'
value.downcase!
if value == 'true'
iter.type, iter.content = 'TrueClass', 'true'
end
when 'TrueClass'
value.downcase!
if value == 'false'
iter.type, iter.content = 'FalseClass', 'false'
end
when 'Numeric'
iter.content =
if value == 'Infinity'
value
else
(Integer(value) rescue Float(value) rescue 0).to_s
end
when 'String'
iter.content = value
when 'Hash', 'Array'
return
else
fail "Unknown type found in model: #{iter.type}"
end
window.change
end
def configure_value(value, type)
value.editable = false
case type
when 'Array', 'Hash'
value.text = ''
when 'TrueClass'
value.text = 'true'
when 'FalseClass'
value.text = 'false'
when 'NilClass'
value.text = 'null'
when 'Numeric', 'String'
value.text ||= ''
value.editable = true
else
raise ArgumentError, "unknown type '#{type}' encountered"
end
end
def add_popup_menu
menu = PopUpMenu.new(self)
menu.create
end
public
# Create a _type_ node with content _content_, and add it to _parent_
# in the model. If _parent_ is nil, create a new model and put it into
# the editor treeview.
def create_node(parent, type, content)
iter = if parent
model.append(parent)
else
new_model = Editor.data2model(nil)
toplevel.view_new_model(new_model)
new_model.iter_first
end
iter.type, iter.content = type, content
expand_collapse(parent) if parent
iter
end
# Ask for a hash key, value pair to be added to the Hash node _parent_.
def ask_for_hash_pair(parent)
key_input = type_input = value_input = nil
dialog = Dialog.new("New (key, value) pair for Hash", nil, nil,
[ Stock::OK, Dialog::RESPONSE_ACCEPT ],
[ Stock::CANCEL, Dialog::RESPONSE_REJECT ]
)
dialog.width_request = 640
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Key:"), false)
hbox.pack_start(key_input = Entry.new)
key_input.text = @key || ''
dialog.vbox.pack_start(hbox, false)
key_input.signal_connect(:activate) do
if parent.any? { |c| c.content == key_input.text }
toplevel.display_status('Key already exists in Hash!')
key_input.text = ''
else
toplevel.display_status('Key has been changed.')
end
end
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Type:"), false)
hbox.pack_start(type_input = ComboBox.new(true))
ALL_TYPES.each { |t| type_input.append_text(t) }
type_input.active = @type || 0
dialog.vbox.pack_start(hbox, false)
type_input.signal_connect(:changed) do
value_input.editable = false
case ALL_TYPES[type_input.active]
when 'Array', 'Hash'
value_input.text = ''
when 'TrueClass'
value_input.text = 'true'
when 'FalseClass'
value_input.text = 'false'
when 'NilClass'
value_input.text = 'null'
else
value_input.text = ''
value_input.editable = true
end
end
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Value:"), false)
hbox.pack_start(value_input = Entry.new)
value_input.width_chars = 60
value_input.text = @value || ''
dialog.vbox.pack_start(hbox, false)
dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER)
dialog.show_all
self.focus = dialog
dialog.run do |response|
if response == Dialog::RESPONSE_ACCEPT
@key = key_input.text
type = ALL_TYPES[@type = type_input.active]
content = value_input.text
return @key, type, content
end
end
return
ensure
dialog.destroy
end
# Ask for an element to be appended _parent_.
def ask_for_element(parent = nil, default_type = nil, value_text = @content)
type_input = value_input = nil
dialog = Dialog.new(
"New element into #{parent ? parent.type : 'root'}",
nil, nil,
[ Stock::OK, Dialog::RESPONSE_ACCEPT ],
[ Stock::CANCEL, Dialog::RESPONSE_REJECT ]
)
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Type:"), false)
hbox.pack_start(type_input = ComboBox.new(true))
default_active = 0
types = parent ? ALL_TYPES : CONTAINER_TYPES
types.each_with_index do |t, i|
type_input.append_text(t)
if t == default_type
default_active = i
end
end
type_input.active = default_active
dialog.vbox.pack_start(hbox, false)
type_input.signal_connect(:changed) do
configure_value(value_input, types[type_input.active])
end
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Value:"), false)
hbox.pack_start(value_input = Entry.new)
value_input.width_chars = 60
value_input.text = value_text if value_text
configure_value(value_input, types[type_input.active])
dialog.vbox.pack_start(hbox, false)
dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER)
dialog.show_all
self.focus = dialog
dialog.run do |response|
if response == Dialog::RESPONSE_ACCEPT
type = types[type_input.active]
@content = case type
when 'Numeric'
if (t = value_input.text) == 'Infinity'
1 / 0.0
else
Integer(t) rescue Float(t) rescue 0
end
else
value_input.text
end.to_s
return type, @content
end
end
return
ensure
dialog.destroy if dialog
end
# Ask for an order criteria for sorting, using _x_ for the element in
# question. Returns the order criterium, and true/false for reverse
# sorting.
def ask_for_order
dialog = Dialog.new(
"Give an order criterium for 'x'.",
nil, nil,
[ Stock::OK, Dialog::RESPONSE_ACCEPT ],
[ Stock::CANCEL, Dialog::RESPONSE_REJECT ]
)
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Order:"), false)
hbox.pack_start(order_input = Entry.new)
order_input.text = @order || 'x'
order_input.width_chars = 60
hbox.pack_start(reverse_checkbox = CheckButton.new('Reverse'), false)
dialog.vbox.pack_start(hbox, false)
dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER)
dialog.show_all
self.focus = dialog
dialog.run do |response|
if response == Dialog::RESPONSE_ACCEPT
return @order = order_input.text, reverse_checkbox.active?
end
end
return
ensure
dialog.destroy if dialog
end
# Ask for a find term to search for in the tree. Returns the term as a
# string.
def ask_for_find_term(search = nil)
dialog = Dialog.new(
"Find a node matching regex in tree.",
nil, nil,
[ Stock::OK, Dialog::RESPONSE_ACCEPT ],
[ Stock::CANCEL, Dialog::RESPONSE_REJECT ]
)
hbox = HBox.new(false, 5)
hbox.pack_start(Label.new("Regex:"), false)
hbox.pack_start(regex_input = Entry.new)
hbox.pack_start(icase_checkbox = CheckButton.new('Icase'), false)
regex_input.width_chars = 60
if search
regex_input.text = search.source
icase_checkbox.active = search.casefold?
end
dialog.vbox.pack_start(hbox, false)
dialog.signal_connect(:'key-press-event', &DEFAULT_DIALOG_KEY_PRESS_HANDLER)
dialog.show_all
self.focus = dialog
dialog.run do |response|
if response == Dialog::RESPONSE_ACCEPT
begin
return Regexp.new(regex_input.text, icase_checkbox.active? ? Regexp::IGNORECASE : 0)
rescue => e
Editor.error_dialog(self, "Evaluation of regex /#{regex_input.text}/ failed: #{e}!")
return
end
end
end
return
ensure
dialog.destroy if dialog
end
# Expand or collapse row pointed to by _iter_ according
# to the #expanded attribute.
def expand_collapse(iter)
if expanded
expand_row(iter.path, true)
else
collapse_row(iter.path)
end
end
end
# The editor main window
class MainWindow < Gtk::Window
include Gtk
| 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/gems/1.8/gems/json_pure-1.4.6/lib/json/pure/parser.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/pure/parser.rb | require 'strscan'
module JSON
module Pure
# This class implements the JSON parser that is used to parse a JSON string
# into a Ruby data structure.
class Parser < StringScanner
STRING = /" ((?:[^\x0-\x1f"\\] |
# escaped special characters:
\\["\\\/bfnrt] |
\\u[0-9a-fA-F]{4} |
# match all but escaped special characters:
\\[\x20-\x21\x23-\x2e\x30-\x5b\x5d-\x61\x63-\x65\x67-\x6d\x6f-\x71\x73\x75-\xff])*)
"/nx
INTEGER = /(-?0|-?[1-9]\d*)/
FLOAT = /(-?
(?:0|[1-9]\d*)
(?:
\.\d+(?i:e[+-]?\d+) |
\.\d+ |
(?i:e[+-]?\d+)
)
)/x
NAN = /NaN/
INFINITY = /Infinity/
MINUS_INFINITY = /-Infinity/
OBJECT_OPEN = /\{/
OBJECT_CLOSE = /\}/
ARRAY_OPEN = /\[/
ARRAY_CLOSE = /\]/
PAIR_DELIMITER = /:/
COLLECTION_DELIMITER = /,/
TRUE = /true/
FALSE = /false/
NULL = /null/
IGNORE = %r(
(?:
//[^\n\r]*[\n\r]| # line comments
/\* # c-style comments
(?:
[^*/]| # normal chars
/[^*]| # slashes that do not start a nested comment
\*[^/]| # asterisks that do not end this comment
/(?=\*/) # single slash before this comment's end
)*
\*/ # the End of this comment
|[ \t\r\n]+ # whitespaces: space, horicontal tab, lf, cr
)+
)mx
UNPARSED = Object.new
# Creates a new JSON::Pure::Parser instance for the string _source_.
#
# It will be configured by the _opts_ hash. _opts_ can have the following
# keys:
# * *max_nesting*: The maximum depth of nesting allowed in the parsed data
# structures. Disable depth checking with :max_nesting => false|nil|0,
# it defaults to 19.
# * *allow_nan*: If set to true, allow NaN, Infinity and -Infinity in
# defiance of RFC 4627 to be parsed by the Parser. This option defaults
# to false.
# * *symbolize_names*: If set to true, returns symbols for the names
# (keys) in a JSON object. Otherwise strings are returned, which is also
# the default.
# * *create_additions*: If set to false, the Parser doesn't create
# additions even if a matchin class and create_id was found. This option
# defaults to true.
# * *object_class*: Defaults to Hash
# * *array_class*: Defaults to Array
def initialize(source, opts = {})
opts ||= {}
if defined?(::Encoding)
if source.encoding == ::Encoding::ASCII_8BIT
b = source[0, 4].bytes.to_a
source = case
when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0
source.dup.force_encoding(::Encoding::UTF_32BE).encode!(::Encoding::UTF_8)
when b.size >= 4 && b[0] == 0 && b[2] == 0
source.dup.force_encoding(::Encoding::UTF_16BE).encode!(::Encoding::UTF_8)
when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0
source.dup.force_encoding(::Encoding::UTF_32LE).encode!(::Encoding::UTF_8)
when b.size >= 4 && b[1] == 0 && b[3] == 0
source.dup.force_encoding(::Encoding::UTF_16LE).encode!(::Encoding::UTF_8)
else
source.dup
end
else
source = source.encode(::Encoding::UTF_8)
end
source.force_encoding(::Encoding::ASCII_8BIT)
else
b = source
source = case
when b.size >= 4 && b[0] == 0 && b[1] == 0 && b[2] == 0
JSON.iconv('utf-8', 'utf-32be', b)
when b.size >= 4 && b[0] == 0 && b[2] == 0
JSON.iconv('utf-8', 'utf-16be', b)
when b.size >= 4 && b[1] == 0 && b[2] == 0 && b[3] == 0
JSON.iconv('utf-8', 'utf-32le', b)
when b.size >= 4 && b[1] == 0 && b[3] == 0
JSON.iconv('utf-8', 'utf-16le', b)
else
b
end
end
super source
if !opts.key?(:max_nesting) # defaults to 19
@max_nesting = 19
elsif opts[:max_nesting]
@max_nesting = opts[:max_nesting]
else
@max_nesting = 0
end
@allow_nan = !!opts[:allow_nan]
@symbolize_names = !!opts[:symbolize_names]
ca = true
ca = opts[:create_additions] if opts.key?(:create_additions)
@create_id = ca ? JSON.create_id : nil
@object_class = opts[:object_class] || Hash
@array_class = opts[:array_class] || Array
end
alias source string
# Parses the current JSON string _source_ and returns the complete data
# structure as a result.
def parse
reset
obj = nil
until eos?
case
when scan(OBJECT_OPEN)
obj and raise ParserError, "source '#{peek(20)}' not in JSON!"
@current_nesting = 1
obj = parse_object
when scan(ARRAY_OPEN)
obj and raise ParserError, "source '#{peek(20)}' not in JSON!"
@current_nesting = 1
obj = parse_array
when skip(IGNORE)
;
else
raise ParserError, "source '#{peek(20)}' not in JSON!"
end
end
obj or raise ParserError, "source did not contain any JSON!"
obj
end
private
# Unescape characters in strings.
UNESCAPE_MAP = Hash.new { |h, k| h[k] = k.chr }
UNESCAPE_MAP.update({
?" => '"',
?\\ => '\\',
?/ => '/',
?b => "\b",
?f => "\f",
?n => "\n",
?r => "\r",
?t => "\t",
?u => nil,
})
def parse_string
if scan(STRING)
return '' if self[1].empty?
string = self[1].gsub(%r((?:\\[\\bfnrt"/]|(?:\\u(?:[A-Fa-f\d]{4}))+|\\[\x20-\xff]))n) do |c|
if u = UNESCAPE_MAP[$&[1]]
u
else # \uXXXX
bytes = ''
i = 0
while c[6 * i] == ?\\ && c[6 * i + 1] == ?u
bytes << c[6 * i + 2, 2].to_i(16) << c[6 * i + 4, 2].to_i(16)
i += 1
end
JSON::UTF16toUTF8.iconv(bytes)
end
end
if string.respond_to?(:force_encoding)
string.force_encoding(::Encoding::UTF_8)
end
string
else
UNPARSED
end
rescue Iconv::Failure => e
raise GeneratorError, "Caught #{e.class}: #{e}"
end
def parse_value
case
when scan(FLOAT)
Float(self[1])
when scan(INTEGER)
Integer(self[1])
when scan(TRUE)
true
when scan(FALSE)
false
when scan(NULL)
nil
when (string = parse_string) != UNPARSED
string
when scan(ARRAY_OPEN)
@current_nesting += 1
ary = parse_array
@current_nesting -= 1
ary
when scan(OBJECT_OPEN)
@current_nesting += 1
obj = parse_object
@current_nesting -= 1
obj
when @allow_nan && scan(NAN)
NaN
when @allow_nan && scan(INFINITY)
Infinity
when @allow_nan && scan(MINUS_INFINITY)
MinusInfinity
else
UNPARSED
end
end
def parse_array
raise NestingError, "nesting of #@current_nesting is too deep" if
@max_nesting.nonzero? && @current_nesting > @max_nesting
result = @array_class.new
delim = false
until eos?
case
when (value = parse_value) != UNPARSED
delim = false
result << value
skip(IGNORE)
if scan(COLLECTION_DELIMITER)
delim = true
elsif match?(ARRAY_CLOSE)
;
else
raise ParserError, "expected ',' or ']' in array at '#{peek(20)}'!"
end
when scan(ARRAY_CLOSE)
if delim
raise ParserError, "expected next element in array at '#{peek(20)}'!"
end
break
when skip(IGNORE)
;
else
raise ParserError, "unexpected token in array at '#{peek(20)}'!"
end
end
result
end
def parse_object
raise NestingError, "nesting of #@current_nesting is too deep" if
@max_nesting.nonzero? && @current_nesting > @max_nesting
result = @object_class.new
delim = false
until eos?
case
when (string = parse_string) != UNPARSED
skip(IGNORE)
unless scan(PAIR_DELIMITER)
raise ParserError, "expected ':' in object at '#{peek(20)}'!"
end
skip(IGNORE)
unless (value = parse_value).equal? UNPARSED
result[@symbolize_names ? string.to_sym : string] = value
delim = false
skip(IGNORE)
if scan(COLLECTION_DELIMITER)
delim = true
elsif match?(OBJECT_CLOSE)
;
else
raise ParserError, "expected ',' or '}' in object at '#{peek(20)}'!"
end
else
raise ParserError, "expected value in object at '#{peek(20)}'!"
end
when scan(OBJECT_CLOSE)
if delim
raise ParserError, "expected next name, value pair in object at '#{peek(20)}'!"
end
if @create_id and klassname = result[@create_id]
klass = JSON.deep_const_get klassname
break unless klass and klass.json_creatable?
result = klass.json_create(result)
end
break
when skip(IGNORE)
;
else
raise ParserError, "unexpected token in object at '#{peek(20)}'!"
end
end
result
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/pure/generator.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/pure/generator.rb | module JSON
MAP = {
"\x0" => '\u0000',
"\x1" => '\u0001',
"\x2" => '\u0002',
"\x3" => '\u0003',
"\x4" => '\u0004',
"\x5" => '\u0005',
"\x6" => '\u0006',
"\x7" => '\u0007',
"\b" => '\b',
"\t" => '\t',
"\n" => '\n',
"\xb" => '\u000b',
"\f" => '\f',
"\r" => '\r',
"\xe" => '\u000e',
"\xf" => '\u000f',
"\x10" => '\u0010',
"\x11" => '\u0011',
"\x12" => '\u0012',
"\x13" => '\u0013',
"\x14" => '\u0014',
"\x15" => '\u0015',
"\x16" => '\u0016',
"\x17" => '\u0017',
"\x18" => '\u0018',
"\x19" => '\u0019',
"\x1a" => '\u001a',
"\x1b" => '\u001b',
"\x1c" => '\u001c',
"\x1d" => '\u001d',
"\x1e" => '\u001e',
"\x1f" => '\u001f',
'"' => '\"',
'\\' => '\\\\',
} # :nodoc:
# Convert a UTF8 encoded Ruby string _string_ to a JSON string, encoded with
# UTF16 big endian characters as \u????, and return it.
if defined?(::Encoding)
def utf8_to_json(string) # :nodoc:
string = string.dup
string << '' # XXX workaround: avoid buffer sharing
string.force_encoding(::Encoding::ASCII_8BIT)
string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] }
string.force_encoding(::Encoding::UTF_8)
string
end
def utf8_to_json_ascii(string) # :nodoc:
string = string.dup
string << '' # XXX workaround: avoid buffer sharing
string.force_encoding(::Encoding::ASCII_8BIT)
string.gsub!(/["\\\x0-\x1f]/) { MAP[$&] }
string.gsub!(/(
(?:
[\xc2-\xdf][\x80-\xbf] |
[\xe0-\xef][\x80-\xbf]{2} |
[\xf0-\xf4][\x80-\xbf]{3}
)+ |
[\x80-\xc1\xf5-\xff] # invalid
)/nx) { |c|
c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
s = JSON::UTF8toUTF16.iconv(c).unpack('H*')[0]
s.gsub!(/.{4}/n, '\\\\u\&')
}
string.force_encoding(::Encoding::UTF_8)
string
rescue Iconv::Failure => e
raise GeneratorError, "Caught #{e.class}: #{e}"
end
else
def utf8_to_json(string) # :nodoc:
string.gsub(/["\\\x0-\x1f]/) { MAP[$&] }
end
def utf8_to_json_ascii(string) # :nodoc:
string = string.gsub(/["\\\x0-\x1f]/) { MAP[$&] }
string.gsub!(/(
(?:
[\xc2-\xdf][\x80-\xbf] |
[\xe0-\xef][\x80-\xbf]{2} |
[\xf0-\xf4][\x80-\xbf]{3}
)+ |
[\x80-\xc1\xf5-\xff] # invalid
)/nx) { |c|
c.size == 1 and raise GeneratorError, "invalid utf8 byte: '#{c}'"
s = JSON::UTF8toUTF16.iconv(c).unpack('H*')[0]
s.gsub!(/.{4}/n, '\\\\u\&')
}
string
rescue Iconv::Failure => e
raise GeneratorError, "Caught #{e.class}: #{e}"
end
end
module_function :utf8_to_json, :utf8_to_json_ascii
module Pure
module Generator
# This class is used to create State instances, that are use to hold data
# while generating a JSON text from a a Ruby data structure.
class State
# Creates a State object from _opts_, which ought to be Hash to create
# a new State instance configured by _opts_, something else to create
# an unconfigured instance. If _opts_ is a State object, it is just
# returned.
def self.from_state(opts)
case opts
when self
opts
when Hash
new(opts)
else
SAFE_STATE_PROTOTYPE.dup
end
end
# Instantiates a new State object, configured by _opts_.
#
# _opts_ can have the following keys:
#
# * *indent*: a string used to indent levels (default: ''),
# * *space*: a string that is put after, a : or , delimiter (default: ''),
# * *space_before*: a string that is put before a : pair delimiter (default: ''),
# * *object_nl*: a string that is put at the end of a JSON object (default: ''),
# * *array_nl*: a string that is put at the end of a JSON array (default: ''),
# * *check_circular*: is deprecated now, use the :max_nesting option instead,
# * *max_nesting*: sets the maximum level of data structure nesting in
# the generated JSON, max_nesting = 0 if no maximum should be checked.
# * *allow_nan*: true if NaN, Infinity, and -Infinity should be
# generated, otherwise an exception is thrown, if these values are
# encountered. This options defaults to false.
def initialize(opts = {})
@indent = ''
@space = ''
@space_before = ''
@object_nl = ''
@array_nl = ''
@allow_nan = false
@ascii_only = false
configure opts
end
# This string is used to indent levels in the JSON text.
attr_accessor :indent
# This string is used to insert a space between the tokens in a JSON
# string.
attr_accessor :space
# This string is used to insert a space before the ':' in JSON objects.
attr_accessor :space_before
# This string is put at the end of a line that holds a JSON object (or
# Hash).
attr_accessor :object_nl
# This string is put at the end of a line that holds a JSON array.
attr_accessor :array_nl
# This integer returns the maximum level of data structure nesting in
# the generated JSON, max_nesting = 0 if no maximum is checked.
attr_accessor :max_nesting
# This integer returns the current depth data structure nesting in the
# generated JSON.
attr_accessor :depth
def check_max_nesting # :nodoc:
return if @max_nesting.zero?
current_nesting = depth + 1
current_nesting > @max_nesting and
raise NestingError, "nesting of #{current_nesting} is too deep"
end
# Returns true, if circular data structures are checked,
# otherwise returns false.
def check_circular?
!@max_nesting.zero?
end
# Returns true if NaN, Infinity, and -Infinity should be considered as
# valid JSON and output.
def allow_nan?
@allow_nan
end
def ascii_only?
@ascii_only
end
# Configure this State instance with the Hash _opts_, and return
# itself.
def configure(opts)
@indent = opts[:indent] if opts.key?(:indent)
@space = opts[:space] if opts.key?(:space)
@space_before = opts[:space_before] if opts.key?(:space_before)
@object_nl = opts[:object_nl] if opts.key?(:object_nl)
@array_nl = opts[:array_nl] if opts.key?(:array_nl)
@allow_nan = !!opts[:allow_nan] if opts.key?(:allow_nan)
@ascii_only = opts[:ascii_only] if opts.key?(:ascii_only)
@depth = opts[:depth] || 0
if !opts.key?(:max_nesting) # defaults to 19
@max_nesting = 19
elsif opts[:max_nesting]
@max_nesting = opts[:max_nesting]
else
@max_nesting = 0
end
self
end
# Returns the configuration instance variables as a hash, that can be
# passed to the configure method.
def to_h
result = {}
for iv in %w[indent space space_before object_nl array_nl allow_nan max_nesting ascii_only depth]
result[iv.intern] = instance_variable_get("@#{iv}")
end
result
end
# Generates a valid JSON document from object +obj+ and returns the
# result. If no valid JSON document can be created this method raises a
# GeneratorError exception.
def generate(obj)
result = obj.to_json(self)
if result !~ /\A\s*(?:\[.*\]|\{.*\})\s*\Z/m
raise GeneratorError, "only generation of JSON objects or arrays allowed"
end
result
end
# Return the value returned by method +name+.
def [](name)
__send__ name
end
end
module GeneratorMethods
module Object
# Converts this object to a string (calling #to_s), converts
# it to a JSON string, and returns the result. This is a fallback, if no
# special method #to_json was defined for some object.
def to_json(*) to_s.to_json end
end
module Hash
# Returns a JSON string containing a JSON object, that is unparsed from
# this Hash instance.
# _state_ is a JSON::State object, that can also be used to configure the
# produced JSON string output further.
# _depth_ is used to find out nesting depth, to indent accordingly.
def to_json(state = nil, *)
state = State.from_state(state)
state.check_max_nesting
json_transform(state)
end
private
def json_shift(state)
state.object_nl.empty? or return ''
state.indent * state.depth
end
def json_transform(state)
delim = ','
delim << state.object_nl
result = '{'
result << state.object_nl
depth = state.depth += 1
first = true
indent = !state.object_nl.empty?
each { |key,value|
result << delim unless first
result << state.indent * depth if indent
result << key.to_s.to_json(state)
result << state.space_before
result << ':'
result << state.space
result << value.to_json(state)
first = false
}
depth = state.depth -= 1
result << state.object_nl
result << state.indent * depth if indent if indent
result << '}'
result
end
end
module Array
# Returns a JSON string containing a JSON array, that is unparsed from
# this Array instance.
# _state_ is a JSON::State object, that can also be used to configure the
# produced JSON string output further.
def to_json(state = nil, *)
state = State.from_state(state)
state.check_max_nesting
json_transform(state)
end
private
def json_transform(state)
delim = ','
delim << state.array_nl
result = '['
result << state.array_nl
depth = state.depth += 1
first = true
indent = !state.array_nl.empty?
each { |value|
result << delim unless first
result << state.indent * depth if indent
result << value.to_json(state)
first = false
}
depth = state.depth -= 1
result << state.array_nl
result << state.indent * depth if indent
result << ']'
end
end
module Integer
# Returns a JSON string representation for this Integer number.
def to_json(*) to_s end
end
module Float
# Returns a JSON string representation for this Float number.
def to_json(state = nil, *)
state = State.from_state(state)
case
when infinite?
if state.allow_nan?
to_s
else
raise GeneratorError, "#{self} not allowed in JSON"
end
when nan?
if state.allow_nan?
to_s
else
raise GeneratorError, "#{self} not allowed in JSON"
end
else
to_s
end
end
end
module String
if defined?(::Encoding)
# This string should be encoded with UTF-8 A call to this method
# returns a JSON string encoded with UTF16 big endian characters as
# \u????.
def to_json(state = nil, *args)
state = State.from_state(state)
if encoding == ::Encoding::UTF_8
string = self
else
string = encode(::Encoding::UTF_8)
end
if state.ascii_only?
'"' << JSON.utf8_to_json_ascii(string) << '"'
else
'"' << JSON.utf8_to_json(string) << '"'
end
end
else
# This string should be encoded with UTF-8 A call to this method
# returns a JSON string encoded with UTF16 big endian characters as
# \u????.
def to_json(state = nil, *args)
state = State.from_state(state)
if state.ascii_only?
'"' << JSON.utf8_to_json_ascii(self) << '"'
else
'"' << JSON.utf8_to_json(self) << '"'
end
end
end
# Module that holds the extinding methods if, the String module is
# included.
module Extend
# Raw Strings are JSON Objects (the raw bytes are stored in an
# array for the key "raw"). The Ruby String can be created by this
# module method.
def json_create(o)
o['raw'].pack('C*')
end
end
# Extends _modul_ with the String::Extend module.
def self.included(modul)
modul.extend Extend
end
# This method creates a raw object hash, that can be nested into
# other data structures and will be unparsed as a raw string. This
# method should be used, if you want to convert raw strings to JSON
# instead of UTF-8 strings, e. g. binary data.
def to_json_raw_object
{
JSON.create_id => self.class.name,
'raw' => self.unpack('C*'),
}
end
# This method creates a JSON text from the result of
# a call to to_json_raw_object of this String.
def to_json_raw(*args)
to_json_raw_object.to_json(*args)
end
end
module TrueClass
# Returns a JSON string for true: 'true'.
def to_json(*) 'true' end
end
module FalseClass
# Returns a JSON string for false: 'false'.
def to_json(*) 'false' end
end
module NilClass
# Returns a JSON string for nil: 'null'.
def to_json(*) 'null' 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/gems/1.8/gems/json_pure-1.4.6/lib/json/add/core.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/add/core.rb | # This file contains implementations of ruby core's custom objects for
# serialisation/deserialisation.
unless Object.const_defined?(:JSON) and ::JSON.const_defined?(:JSON_LOADED) and
::JSON::JSON_LOADED
require 'json'
end
require 'date'
class Symbol
def to_json(*a)
{
JSON.create_id => self.class.name,
's' => to_s,
}.to_json(*a)
end
def self.json_create(o)
o['s'].to_sym
end
end
class Time
def self.json_create(object)
if usec = object.delete('u') # used to be tv_usec -> tv_nsec
object['n'] = usec * 1000
end
if respond_to?(:tv_nsec)
at(*object.values_at('s', 'n'))
else
at(object['s'], object['n'] / 1000)
end
end
def to_json(*args)
{
JSON.create_id => self.class.name,
's' => tv_sec,
'n' => respond_to?(:tv_nsec) ? tv_nsec : tv_usec * 1000
}.to_json(*args)
end
end
class Date
def self.json_create(object)
civil(*object.values_at('y', 'm', 'd', 'sg'))
end
alias start sg unless method_defined?(:start)
def to_json(*args)
{
JSON.create_id => self.class.name,
'y' => year,
'm' => month,
'd' => day,
'sg' => start,
}.to_json(*args)
end
end
class DateTime
def self.json_create(object)
args = object.values_at('y', 'm', 'd', 'H', 'M', 'S')
of_a, of_b = object['of'].split('/')
if of_b and of_b != '0'
args << Rational(of_a.to_i, of_b.to_i)
else
args << of_a
end
args << object['sg']
civil(*args)
end
alias start sg unless method_defined?(:start)
def to_json(*args)
{
JSON.create_id => self.class.name,
'y' => year,
'm' => month,
'd' => day,
'H' => hour,
'M' => min,
'S' => sec,
'of' => offset.to_s,
'sg' => start,
}.to_json(*args)
end
end
class Range
def self.json_create(object)
new(*object['a'])
end
def to_json(*args)
{
JSON.create_id => self.class.name,
'a' => [ first, last, exclude_end? ]
}.to_json(*args)
end
end
class Struct
def self.json_create(object)
new(*object['v'])
end
def to_json(*args)
klass = self.class.name
klass.to_s.empty? and raise JSON::JSONError, "Only named structs are supported!"
{
JSON.create_id => klass,
'v' => values,
}.to_json(*args)
end
end
class Exception
def self.json_create(object)
result = new(object['m'])
result.set_backtrace object['b']
result
end
def to_json(*args)
{
JSON.create_id => self.class.name,
'm' => message,
'b' => backtrace,
}.to_json(*args)
end
end
class Regexp
def self.json_create(object)
new(object['s'], object['o'])
end
def to_json(*)
{
JSON.create_id => self.class.name,
'o' => options,
's' => source,
}.to_json
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/gems/1.8/gems/json_pure-1.4.6/lib/json/add/rails.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/json_pure-1.4.6/lib/json/add/rails.rb | # This file contains implementations of rails custom objects for
# serialisation/deserialisation.
unless Object.const_defined?(:JSON) and ::JSON.const_defined?(:JSON_LOADED) and
::JSON::JSON_LOADED
require 'json'
end
class Object
def self.json_create(object)
obj = new
for key, value in object
next if key == JSON.create_id
instance_variable_set "@#{key}", value
end
obj
end
def to_json(*a)
result = {
JSON.create_id => self.class.name
}
instance_variables.inject(result) do |r, name|
r[name[1..-1]] = instance_variable_get name
r
end
result.to_json(*a)
end
end
class Symbol
def to_json(*a)
to_s.to_json(*a)
end
end
module Enumerable
def to_json(*a)
to_a.to_json(*a)
end
end
# class Regexp
# def to_json(*)
# inspect
# end
# end
#
# The above rails definition has some problems:
#
# 1. { 'foo' => /bar/ }.to_json # => "{foo: /bar/}"
# This isn't valid JSON, because the regular expression syntax is not
# defined in RFC 4627. (And unquoted strings are disallowed there, too.)
# Though it is valid Javascript.
#
# 2. { 'foo' => /bar/mix }.to_json # => "{foo: /bar/mix}"
# This isn't even valid Javascript.
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_multibyte_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_multibyte_test.rb | require 'jdbc_common'
require 'db/mysql'
class MySQLMultibyteTest < Test::Unit::TestCase
include MultibyteTestMethods
end
class MySQLNonUTF8EncodingTest < Test::Unit::TestCase
include NonUTF8EncodingMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_limit_offset_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_limit_offset_test.rb | require 'jdbc_common'
require 'db/mssql'
ActiveRecord::Schema.verbose = false
class CreateLongShips < ActiveRecord::Migration
def self.up
create_table "long_ships", :force => true do |t|
t.string "name", :limit => 50, :null => false
t.integer "width", :default => 123
t.integer "length", :default => 456
end
end
def self.down
drop_table "long_ships"
end
end
class LongShip < ActiveRecord::Base
has_many :vikings
end
class CreateVikings < ActiveRecord::Migration
def self.up
create_table "vikings", :force => true do |t|
t.integer "long_ship_id", :null => false
t.string "name", :limit => 50, :default => "Sven"
end
end
def self.down
drop_table "vikings"
end
end
class Viking < ActiveRecord::Base
belongs_to :long_ship
end
class MsSQLLimitOffsetTest < Test::Unit::TestCase
def setup
CreateLongShips.up
CreateVikings.up
@connection = ActiveRecord::Base.connection
end
def teardown
CreateVikings.down
CreateLongShips.down
ActiveRecord::Base.clear_active_connections!
end
def test_limit_and_offset
%w(one two three four five six seven eight).each do |name|
LongShip.create!(:name => name)
end
ship_names = LongShip.find(:all, :offset => 2, :limit => 3).map(&:name)
assert_equal(%w(three four five), ship_names)
end
def test_limit_and_offset_with_order
%w(one two three four five six seven eight).each do |name|
LongShip.create!(:name => name)
end
ship_names = LongShip.find(:all, :order => "name", :offset => 4, :limit => 2).map(&:name)
assert_equal(%w(seven six), ship_names)
end
# TODO: work out how to fix DISTINCT support without breaking :include
# def test_limit_and_offset_with_distinct
# %w(c a b a b a c d c d).each do |name|
# LongShip.create!(:name => name)
# end
# ship_names = LongShip.find(:all, :select => "DISTINCT name", :order => "name", :offset => 1, :limit => 2).map(&:name)
# assert_equal(%w(b c), ship_names)
# end
def test_limit_and_offset_with_include
skei = LongShip.create!(:name => "Skei")
skei.vikings.create!(:name => "Bob")
skei.vikings.create!(:name => "Ben")
skei.vikings.create!(:name => "Basil")
ships = Viking.find(:all, :include => :long_ship, :offset => 1, :limit => 2)
assert_equal(2, ships.size)
end
def test_limit_and_offset_with_include_and_order
boat1 = LongShip.create!(:name => "1-Skei")
boat2 = LongShip.create!(:name => "2-Skei")
boat1.vikings.create!(:name => "Adam")
boat2.vikings.create!(:name => "Ben")
boat1.vikings.create!(:name => "Carl")
boat2.vikings.create!(:name => "Donald")
vikings = Viking.find(:all, :include => :long_ship, :order => "long_ships.name, vikings.name", :offset => 0, :limit => 3)
assert_equal(["Adam", "Carl", "Ben"], vikings.map(&: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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_reserved_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_reserved_test.rb | require 'jdbc_common'
require 'db/postgres'
require 'models/reserved_word'
class PostgresReservedWordsTest < Test::Unit::TestCase
def setup
CreateReservedWords.up
end
def teardown
CreateReservedWords.down
end
def test_quote_reserved_word_column
columns = ReservedWord.column_names - ["id"]
ReservedWord.connection.add_index :reserved_words, columns
indexes = ReservedWord.connection.indexes("reserved_words")
assert_equal 1, indexes.size
columns.each do |c|
assert indexes[0].columns.include?(c), "#{indexes[0].columns.inspect} does not include #{c.inspect}"
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit.rb |
$silentTests = false
$testnum=0
$ntest=0
$failed = []
$curtestOK=true
module MiniRUnit
class Failure
def initialize(what, testnum, msg, where)
@what, @testnum, @msg, @where = what, testnum, msg, where
end
def to_s
sprintf("FAILED %s %d %s-- %s\n", @what, @testnum, @msg, @where)
end
end
class Error
def initialize(what, testnum, boom)
@what, @testnum, @boom = what, testnum, boom
end
def to_s
sprintf("EXCEPTION raised %s %d -- \n\tException: %s\n\t%s",
@what, @testnum, @boom.to_s, @boom.backtrace.join("\n\t"))
end
end
end
def test_check(what)
printf "%s : ", what unless $silentTests
$what = what
$testnum = 0
end
def test_ok(cond, msg="")
$testnum+=1
$ntest+=1
if cond
print "." unless $silentTests
else
where = caller.reject {|where| where =~ /minirunit/}[0]
$failed.push(MiniRUnit::Failure.new($what, $testnum, msg, where))
print "F" unless $silentTests
$curtestOK=false
end
end
def test_fail(msg="")
test_ok(false, msg)
end
def test_equal(a,b)
test_ok(a == b, "expected #{a.inspect}, found #{b.inspect}")
end
def test_no_exception(&proc)
raised = false
begin
proc.call
rescue exception
raised = x
end
test_ok(!raised, "unexpected exception #{raised}")
end
def test_exception(type=Exception, &proc)
raised = false
begin
proc.call
rescue type=>e
raised = true
end
test_ok(raised, "#{type} expected")
e
end
def test_get_last_failed
if $failed.empty?
return nil
end
return $failed.last
end
def test_print_report
puts
puts "-" * 80
$failed.each { |error| puts error }
puts "-" * 80
puts "Tests: #$ntest. (Ok: #{$ntest - $failed.size}; Failed: #{$failed.size})"
end
def test_load(test)
begin
$curtestOK=true
load(test)
rescue Exception => boom
puts 'ERROR' unless $silentTests
$failed.push(MiniRUnit::Error.new($what, $testnum, boom))
else
if $curtestOK
puts 'OK' unless $silentTests
else
puts 'FAILED' unless $silentTests
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/has_many_through.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/has_many_through.rb | class CreateRbac < ActiveRecord::Migration
def self.up
create_table :role_assignments do |t|
t.column :role_id, :integer
t.column :user_id, :integer
end
create_table :roles do |t|
t.column :name, :string
t.column :description, :string
end
create_table :permission_groups do |t|
t.column :right_id, :integer
t.column :role_id, :integer
end
create_table :rights do |t|
t.column :name, :string
t.column :controller_name, :string
t.column :actions, :string
t.column :hours, :float, :null => false
end
end
def self.down
drop_table :role_assignments
drop_table :roles
drop_table :permission_groups
drop_table :rights
end
end
class Right < ActiveRecord::Base
has_many :permission_groups, :dependent => :destroy
has_many :roles, :through => :permission_groups
end
class Role < ActiveRecord::Base
has_many :permission_groups, :dependent => :destroy
has_many :rights, :through => :permission_groups
has_many :role_assignments, :dependent => :destroy
end
class PermissionGroup < ActiveRecord::Base
belongs_to :right
belongs_to :role
end
class RoleAssignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
module HasManyThroughMethods
def setup
CreateRbac.up
end
def teardown
CreateRbac.down
end
def test_has_many_through
admin_role = Role.create( {:name => "Administrator", :description => "System defined super user - access to right and role management."} )
admin_role.save
assert_equal(0, admin_role.rights.sum(:hours))
role_rights = Right.create( {:name => "Administrator - Full Access To Roles", :actions => "*", :controller_name => "Admin::RolesController", :hours => 0} )
right_rights = Right.create( {:name => "Administrator - Full Access To Rights", :actions => "*", :controller_name => "Admin::RightsController", :hours => 1.5} )
admin_role.rights << role_rights
admin_role.rights << right_rights
admin_role.save
assert_equal(1.5, admin_role.rights.sum(:hours))
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_identity_insert_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_identity_insert_test.rb | require 'jdbc_common'
require 'db/mssql'
class MsSQLIdentityInsertTest < Test::Unit::TestCase
include MigrationSetup
def test_enable_identity_insert_when_necessary
Entry.connection.execute("INSERT INTO entries([id], [title]) VALUES (333, 'Title')")
Entry.connection.execute("INSERT INTO entries([title], [id]) VALUES ('Title', 344)")
Entry.connection.execute("INSERT INTO entries(id, title) VALUES (666, 'Title')")
Entry.connection.execute("INSERT INTO entries(id, title) (SELECT id+123, title FROM entries)")
end
def test_dont_enable_identity_insert_when_unnecessary
Entry.connection.execute("INSERT INTO entries([title]) VALUES ('[id]')")
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/generic_jdbc_connection_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/generic_jdbc_connection_test.rb | require 'jdbc_common'
require 'db/jdbc'
class GenericJdbcConnectionTest < Test::Unit::TestCase
def test_connection_available_through_jdbc_adapter
ActiveRecord::Base.connection.execute("show databases");
assert ActiveRecord::Base.connected?
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_nonstandard_primary_key_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_nonstandard_primary_key_test.rb | require 'jdbc_common'
require 'db/mysql'
class Project < ActiveRecord::Migration
def self.up
create_table :project, :primary_key => "project_id" do |t|
t.string :projectType, :limit => 31
t.boolean :published
t.datetime :created_date
t.text :abstract, :title
end
end
def self.down
drop_table :project
end
end
class MysqlNonstandardPrimaryKeyTest < Test::Unit::TestCase
def setup
Project.up
end
def teardown
Project.down
end
def standard_dump
stream = StringIO.new
ActiveRecord::SchemaDumper.ignore_tables = []
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
stream.string
end
def test_nonstandard_primary_key
output = standard_dump
assert_match %r(:primary_key => "project_id"), output, "non-standard primary key not preserved"
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/manualTestDatabase.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/manualTestDatabase.rb | #!/usr/bin/env jruby
if ARGV.length < 2
$stderr.puts "syntax: #{__FILE__} [filename] [configuration-name]"
$stderr.puts " where filename points to a YAML database configuration file"
$stderr.puts " and the configuration name is in this file"
exit
end
$:.unshift File.join(File.dirname(__FILE__),'..','lib')
require 'yaml'
require 'rubygems'
RAILS_CONNECTION_ADAPTERS = ['mysql', 'jdbc']
require 'active_record'
cfg = (File.open(ARGV[0]) {|f| YAML.load(f) })[ARGV[1]]
ActiveRecord::Base.establish_connection(cfg)
ActiveRecord::Schema.define do
drop_table :authors rescue nil
drop_table :author rescue nil
create_table :author, :force => true do |t|
t.column :name, :string, :null => false
end
# Exercise all types, and add_column
add_column :author, :description, :text
add_column :author, :descr, :string, :limit => 50
add_column :author, :age, :integer, :null => false, :default => 17
add_column :author, :weight, :float
add_column :author, :born, :datetime
add_column :author, :died, :timestamp
add_column :author, :wakeup_time, :time
add_column :author, :birth_date, :date
add_column :author, :private_key, :binary
add_column :author, :female, :boolean, :default => true
change_column :author, :descr, :string, :limit => 100 if /db2|derby/ !~ ARGV[1]
change_column_default :author, :female, false if /db2|derby|mssql|firebird/ !~ ARGV[1]
remove_column :author, :died if /db2|derby/ !~ ARGV[1]
rename_column :author, :wakeup_time, :waking_time if /db2|derby|mimer/ !~ ARGV[1]
add_index :author, :name, :unique if /db2/ !~ ARGV[1]
add_index :author, [:age,:female], :name => :is_age_female if /db2/ !~ ARGV[1]
remove_index :author, :name if /db2/ !~ ARGV[1]
remove_index :author, :name => :is_age_female if /db2/ !~ ARGV[1]
rename_table :author, :authors if /db2|firebird|mimer/ !~ ARGV[1]
create_table :products, :force => true do |t|
t.column :title, :string
t.column :description, :text
t.column :image_url, :string
end
add_column :products, :price, :float, :default => 0.0
create_table :orders, :force => true do |t|
t.column :name, :string
t.column :address, :text
t.column :email, :string
t.column :pay_type, :string, :limit => 10
end
create_table :line_items, :force => true do |t|
t.column :product_id, :integer, :null => false
t.column :order_id, :integer, :null => false
t.column :quantity, :integer, :null => false
t.column :total_price, :float, :null => false
end
end
class Author < ActiveRecord::Base;
set_table_name "author" if /db2|firebird|mimer/ =~ ARGV[1]
end
class Order < ActiveRecord::Base
has_many :line_items
end
class Product < ActiveRecord::Base
has_many :orders, :through => :line_items
has_many :line_items
def self.find_products_for_sale
find(:all, :order => "title")
end
end
class LineItem < ActiveRecord::Base
belongs_to :order
belongs_to :product
end
Product.create(:title => 'Pragmatic Project Automation',
:description =>
%{<p>
<em>Pragmatic Project Automation</em> shows you how to improve the
consistency and repeatability of your project's procedures using
automation to reduce risk and errors.
</p>
<p>
Simply put, we're going to put this thing called a computer to work
for you doing the mundane (but important) project stuff. That means
you'll have more time and energy to do the really
exciting---and difficult---stuff, like writing quality code.
</p>},
:image_url => '/images/auto.jpg',
:price => 29.95)
Product.create(:title => 'Pragmatic Version Control',
:description =>
%{<p>
This book is a recipe-based approach to using Subversion that will
get you up and
running quickly---and correctly. All projects need version control:
it's a foundational piece of any project's infrastructure. Yet half
of all project teams in the U.S. don't use any version control at all.
Many others don't use it well, and end up experiencing time-consuming problems.
</p>},
:image_url => '/images/svn.jpg',
:price => 28.50)
# . . .
Product.create(:title => 'Pragmatic Unit Testing (C#)',
:description =>
%{<p>
Pragmatic programmers use feedback to drive their development and
personal processes. The most valuable feedback you can get while
coding comes from unit testing.
</p>
<p>
Without good tests in place, coding can become a frustrating game of
"whack-a-mole." That's the carnival game where the player strikes at a
mechanical mole; it retreats and another mole pops up on the opposite side
of the field. The moles pop up and down so fast that you end up flailing
your mallet helplessly as the moles continue to pop up where you least
expect them.
</p>},
:image_url => '/images/utc.jpg',
:price => 27.75)
1.times do
$stderr.print '.'
Author.destroy_all
Author.create(:name => "Arne Svensson", :age => 30)
if /db2|derby|mimer/ !~ ARGV[1]
Author.create(:name => "Pelle Gogolsson", :age => 15, :waking_time => Time.now, :private_key => "afbafddsfgsdfg")
else
Author.create(:name => "Pelle Gogolsson", :age => 15, :wakeup_time => Time.now, :private_key => "afbafddsfgsdfg")
end
Author.find(:first)
Author.find(:all)
arne = Author.find(:first)
arne.destroy
pelle = Author.find(:first)
pelle.name = "Pelle Sweitchon"
pelle.description = "dfsssdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
pelle.descr = "adsfasdf"
pelle.age = 79
pelle.weight = 57.6
pelle.born = Time.gm(1982,8,13,10,15,3,0)
pelle.female = false
pelle.save
prods = Product.find :all
order = Order.new(:name => "Dalai Lama", :address => "Great Road 32", :email => "abc@dot.com", :pay_type => "cash")
order.line_items << LineItem.new(:product => prods[0], :quantity => 3, :total_price => (prods[0].price * 3))
order.line_items << LineItem.new(:product => prods[2], :quantity => 1, :total_price => (prods[2].price))
order.save
puts "order: #{order.line_items.inspect}, with id: #{order.id} and name: #{order.name}"
end
ActiveRecord::Schema.define do
drop_table :line_items
drop_table :orders
drop_table :products
drop_table((/db2|firebird|mimer/=~ARGV[1]? :author : :authors ))
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_multibyte_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_multibyte_test.rb | #! /usr/bin/env jruby
require 'jdbc_common'
require 'db/mssql'
class MsSQLMultibyteTest < Test::Unit::TestCase
include MultibyteTestMethods
def test_select_multibyte_string
Entry.create!(:title => 'テスト', :content => '本文')
entry = Entry.find(:last)
assert_equal "テスト", entry.title
assert_equal "本文", entry.content
assert_equal entry, Entry.find_by_title("テスト")
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/derby_migration_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/derby_migration_test.rb | require 'jdbc_common'
require 'db/derby'
class CreateDummies < ActiveRecord::Migration
def self.up
create_table :dummies, :force => true do |t|
t.string :year, :default => "", :null => false
end
add_index :dummies, :year, :unique => true
end
end
class DerbyQuotingTest < Test::Unit::TestCase
include FixtureSetup
def test_create_table_column_quoting_vs_keywords
CreateDummies.up
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/hsqldb_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/hsqldb_simple_test.rb | require 'jdbc_common'
require 'db/hsqldb'
class HsqldbSimpleTest < Test::Unit::TestCase
include SimpleTestMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/sqlite3_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/sqlite3_simple_test.rb | require 'jdbc_common'
require 'db/sqlite3'
require 'models/data_types'
require 'models/validates_uniqueness_of_string'
class SQLite3SimpleTest < Test::Unit::TestCase
include SimpleTestMethods
include ActiveRecord3TestMethods
def test_recreate_database
assert @connection.tables.include?(Entry.table_name)
db = @connection.database_name
@connection.recreate_database(db)
assert (not @connection.tables.include? Entry.table_name)
self.setup # avoid teardown complaining
end
def test_execute_insert
assert_equal 1, Entry.count
id = @connection.execute "INSERT INTO entries (title, content) VALUES ('Execute Insert', 'This now works with SQLite3')"
assert_equal Entry.last.id, id
assert_equal 2, Entry.count
end
def test_execute_update
affected_rows = @connection.execute "UPDATE entries SET title = 'Execute Update' WHERE id = #{Entry.first.id}"
assert_equal 1, affected_rows
assert_equal 'Execute Update', Entry.first.title
end
def test_columns
cols = ActiveRecord::Base.connection.columns("entries")
assert cols.find {|col| col.name == "title"}
end
def test_remove_column
assert_nothing_raised do
ActiveRecord::Schema.define do
add_column "entries", "test_remove_column", :string
end
end
cols = ActiveRecord::Base.connection.columns("entries")
assert cols.find {|col| col.name == "test_remove_column"}
assert_nothing_raised do
ActiveRecord::Schema.define do
remove_column "entries", "test_remove_column"
end
end
cols = ActiveRecord::Base.connection.columns("entries")
assert !cols.find {|col| col.name == "test_remove_column"}
end
def test_rename_column
assert_nothing_raised do
ActiveRecord::Schema.define do
rename_column "entries", "title", "name"
end
end
cols = ActiveRecord::Base.connection.columns("entries")
assert cols.find {|col| col.name == "name"}
assert !cols.find {|col| col.name == "title"}
assert_nothing_raised do
ActiveRecord::Schema.define do
rename_column "entries", "name", "title"
end
end
cols = ActiveRecord::Base.connection.columns("entries")
assert cols.find {|col| col.name == "title"}
assert !cols.find {|col| col.name == "name"}
end
def test_rename_column_preserves_content
post = Entry.find(:first)
assert_equal @title, post.title
assert_equal @content, post.content
assert_equal @rating, post.rating
assert_nothing_raised do
ActiveRecord::Schema.define do
rename_column "entries", "title", "name"
end
end
post = Entry.find(:first)
assert_equal @title, post.name
assert_equal @content, post.content
assert_equal @rating, post.rating
end
def test_rename_column_preserves_index
assert_equal(0, @connection.indexes(:entries).size)
index_name = "entries_index"
assert_nothing_raised do
ActiveRecord::Schema.define do
add_index "entries", "title", :name => index_name
end
end
indexes = @connection.indexes(:entries)
assert_equal(1, indexes.size)
assert_equal "entries", indexes.first.table.to_s
assert_equal index_name, indexes.first.name
assert !indexes.first.unique
assert_equal ["title"], indexes.first.columns
assert_nothing_raised do
ActiveRecord::Schema.define do
rename_column "entries", "title", "name"
end
end
indexes = @connection.indexes(:entries)
assert_equal(1, indexes.size)
assert_equal "entries", indexes.first.table.to_s
assert_equal index_name, indexes.first.name
assert !indexes.first.unique
assert_equal ["name"], indexes.first.columns
end
def test_change_column_default
assert_nothing_raised do
ActiveRecord::Schema.define do
add_column "entries", "test_change_column_default", :string, :default => "unchanged"
end
end
cols = ActiveRecord::Base.connection.columns("entries")
col = cols.find{|col| col.name == "test_change_column_default"}
assert col
assert_equal col.default, 'unchanged'
assert_nothing_raised do
ActiveRecord::Schema.define do
change_column_default "entries", "test_change_column_default", "changed"
end
end
cols = ActiveRecord::Base.connection.columns("entries")
col = cols.find{|col| col.name == "test_change_column_default"}
assert col
assert_equal col.default, 'changed'
end
def test_change_column
assert_nothing_raised do
ActiveRecord::Schema.define do
add_column "entries", "test_change_column", :string
end
end
cols = ActiveRecord::Base.connection.columns("entries")
col = cols.find{|col| col.name == "test_change_column"}
assert col
assert_equal col.type, :string
assert_nothing_raised do
ActiveRecord::Schema.define do
change_column "entries", "test_change_column", :integer
end
end
cols = ActiveRecord::Base.connection.columns("entries")
col = cols.find{|col| col.name == "test_change_column"}
assert col
assert_equal col.type, :integer
end
end
# assert_raise ActiveRecord::RecordInvalid do
class SQLite3HasManyThroughTest < Test::Unit::TestCase
include HasManyThroughMethods
end
if jruby?
JInteger = java.lang.Integer
else
JInteger = Fixnum
class Fixnum
# Arbitrary value...we could pick
MAX_VALUE = 2
end
end
class SQLite3TypeConversionTest < Test::Unit::TestCase
TEST_TIME = Time.at(1169964202)
TEST_BINARY = "Some random binary data % \0 and then some"
def setup
DbTypeMigration.up
DbType.create(
:sample_timestamp => TEST_TIME,
:sample_datetime => TEST_TIME,
:sample_time => TEST_TIME,
:sample_date => TEST_TIME,
:sample_decimal => JInteger::MAX_VALUE + 1,
:sample_small_decimal => 3.14,
:sample_binary => TEST_BINARY)
end
def teardown
DbTypeMigration.down
end
def test_decimal
types = DbType.find(:first)
assert_equal((JInteger::MAX_VALUE + 1), types.sample_decimal)
end
def test_decimal_scale
types = DbType.find(:first)
assert_equal(2, DbType.columns_hash["sample_small_decimal"].scale)
end
def test_decimal_precision
types = DbType.find(:first)
assert_equal(3, DbType.columns_hash["sample_small_decimal"].precision)
end
def test_binary
types = DbType.find(:first)
assert_equal(TEST_BINARY, types.sample_binary)
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_mixed_case_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_mixed_case_test.rb | require 'jdbc_common'
require 'models/mixed_case'
class MixedCaseTest < Test::Unit::TestCase
def setup
Migration::MixedCase.up
end
def teardown
Migration::MixedCase.down
end
def test_create
mixed_case = MixedCase.create :SOME_value => 'some value'
assert_equal 'some value', mixed_case.SOME_value
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/informix_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/informix_simple_test.rb | # -*- coding: utf-8 -*-
#
# To run this script, run the following:
#
# CREATE DATABASE weblog_development;
#
# TODO: Finish the explanation.
require 'jdbc_common'
require 'db/informix'
class InformixSimpleTest < Test::Unit::TestCase
include SimpleTestMethods
# Informix does not like "= NULL".
def test_equals_null
Entry.create!(:title => "Foo")
entry = Entry.find(:first, :conditions => ["content = NULL"])
assert_equal "Foo", entry.title
end
# Informix does not like "!= NULL" or "<> NULL".
def test_not_equals_null
Entry.create!(:title => "Foo", :content => "Bar")
entry = Entry.find_by_title("Foo", :conditions => ["content != NULL"])
assert_equal "Foo", entry.title
entry = Entry.find_by_title("Foo", :conditions => ["content <> NULL"])
assert_equal "Foo", entry.title
end
end
class InformixMultibyteTest < Test::Unit::TestCase
include MultibyteTestMethods
# Overriding the included test since we can't create text fields via a
# simple insert in Informix.
def test_select_multibyte_string
Entry.create!(:title => 'テスト', :content => '本文')
entry = Entry.find(:first)
assert_equal "テスト", entry.title
assert_equal "本文", entry.content
assert_equal entry, Entry.find_by_title("テスト")
end
end
class InformixHasManyThroughTest < Test::Unit::TestCase
include HasManyThroughMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_schema_search_path_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_schema_search_path_test.rb | require 'rubygems'
require 'active_record'
require 'jdbc_common'
require 'db/postgres'
class CreateSchema < ActiveRecord::Migration
def self.up
execute "CREATE SCHEMA test"
execute "CREATE TABLE test.people (id serial, name text)"
execute "INSERT INTO test.people (name) VALUES ('Alex')"
execute "CREATE TABLE public.people (id serial, wrongname text)"
end
def self.down
execute "DROP SCHEMA test CASCADE"
execute "DROP TABLE people"
end
end
class Person < ActiveRecord::Base
establish_connection POSTGRES_CONFIG.merge(:schema_search_path => 'test')
end
class PostgresSchemaSearchPathTest < Test::Unit::TestCase
def setup
CreateSchema.up
end
def teardown
CreateSchema.down
end
def test_columns
assert_equal(%w{id name}, Person.column_names)
end
def test_find_right
assert_not_nil Person.find_by_name("Alex")
end
def test_find_wrong
assert_raise NoMethodError do
Person.find_by_wrongname("Alex")
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/oracle_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/oracle_simple_test.rb | require 'jdbc_common'
require 'db/oracle'
class OracleSimpleTest < Test::Unit::TestCase
include SimpleTestMethods
end
class OracleSpecificTest < Test::Unit::TestCase
include MultibyteTestMethods # so we can get @java_con
def setup
super
@java_con.createStatement.execute "CREATE TABLE DEFAULT_NUMBER (VALUE NUMBER, DATUM DATE)"
@java_con.createStatement.execute "INSERT INTO DEFAULT_NUMBER (VALUE, DATUM) VALUES (0.076, TIMESTAMP'2009-11-05 00:00:00')"
@java_con.createStatement.execute "CREATE SYNONYM POSTS FOR ENTRIES"
@klass = Class.new(ActiveRecord::Base)
@klass.set_table_name "DEFAULT_NUMBER"
end
def teardown
@java_con.createStatement.execute "DROP TABLE DEFAULT_NUMBER"
@java_con.createStatement.execute "DROP SYNONYM POSTS"
super
end
def test_default_number_precision
obj = @klass.find(:first)
assert_equal 0.076, obj.value
end
# JRUBY-3675, ACTIVERECORD_JDBC-22
def test_load_date
obj = @klass.find(:first)
assert_not_nil obj.datum, "no date"
end
def test_load_null_date
@java_con.createStatement.execute "UPDATE DEFAULT_NUMBER SET DATUM = NULL"
obj = @klass.find(:first)
assert obj.datum.nil?
end
def test_model_access_by_synonym
@klass.set_table_name "POSTS"
entry_columns = Entry.columns_hash
@klass.columns.each do |c|
ec = entry_columns[c.name]
assert ec
assert_equal ec.sql_type, c.sql_type
assert_equal ec.type, c.type
end
end
end if defined?(JRUBY_VERSION)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/pick_rails_version.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/pick_rails_version.rb | # Specify version of activerecord with ENV['AR_VERSION'] if desired
gem 'rails', ENV['AR_VERSION'] if ENV['AR_VERSION']
require 'active_record/version'
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jndi_callbacks_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jndi_callbacks_test.rb | require 'jdbc_common'
begin
require 'mocha'
class JndiConnectionPoolCallbacksTest < Test::Unit::TestCase
def setup
@connection = mock "JdbcConnection"
@connection.stubs(:jndi_connection?).returns(true)
@connection.stubs(:adapter=)
@logger = mock "logger"
@config = { :jndi => "jdbc/some_pool", :adapter => "mysql" }
Entry.connection_pool.disconnect!
assert !Entry.connection_pool.connected?
class << Entry.connection_pool; public :instance_variable_set; end
end
def teardown
@connection.stubs(:disconnect!)
Entry.connection_pool.disconnect!
end
def test_should_call_hooks_on_checkout_and_checkin
@connection.expects(:disconnect!)
@adapter = ActiveRecord::ConnectionAdapters::JdbcAdapter.new @connection, @logger, @config
Entry.connection_pool.instance_variable_set "@connections", [@adapter]
@connection.expects(:reconnect!)
Entry.connection_pool.checkout
@connection.expects(:disconnect!)
Entry.connection_pool.checkin @adapter
end
end
rescue LoadError
warn "mocha not found, disabling mocha-based tests"
end if ActiveRecord::Base.respond_to?(:connection_pool)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_simple_test.rb | # To run this script, run the following in a mysql instance:
#
# drop database if exists weblog_development;
# create database weblog_development;
# grant all on weblog_development.* to blog@localhost;
# flush privileges;
require 'jdbc_common'
require 'db/mysql'
class MysqlSimpleTest < Test::Unit::TestCase
include SimpleTestMethods
include ActiveRecord3TestMethods
def test_string_quoting_oddity
s = "0123456789a'a"
assert_equal "'0123456789a\\'a'", ActiveRecord::Base.connection.quote(s)
s2 = s[10,3]
assert_equal "a'a", s2
assert_equal "'a\\'a'", ActiveRecord::Base.connection.quote(s2)
end
def test_table_name_quoting_with_dot
s = "weblog_development.posts"
assert_equal "`weblog_development`.`posts`", ActiveRecord::Base.connection.quote_table_name(s)
end
end
class MysqlHasManyThroughTest < Test::Unit::TestCase
include HasManyThroughMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/sybase_jtds_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/sybase_jtds_simple_test.rb | require 'jdbc_common'
require 'db/sybase_jtds'
class SybaseJtdsSimpleTest < Test::Unit::TestCase
include SimpleTestMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/simple.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/simple.rb | # -*- coding: utf-8 -*-
ActiveRecord::Schema.verbose = false
ActiveRecord::Base.time_zone_aware_attributes = true if ActiveRecord::Base.respond_to?(:time_zone_aware_attributes)
ActiveRecord::Base.default_timezone = :utc
#just a random zone, unlikely to be local, and not utc
Time.zone = 'Moscow' if Time.respond_to?(:zone)
module MigrationSetup
def setup
DbTypeMigration.up
CreateStringIds.up
CreateEntries.up
CreateAutoIds.up
CreateValidatesUniquenessOf.up
@connection = ActiveRecord::Base.connection
end
def teardown
DbTypeMigration.down
CreateStringIds.down
CreateEntries.down
CreateAutoIds.down
CreateValidatesUniquenessOf.down
ActiveRecord::Base.clear_active_connections!
end
end
module FixtureSetup
include MigrationSetup
def setup
super
@title = "First post!"
@content = "Hello from JRuby on Rails!"
@new_title = "First post updated title"
@rating = 205.76
@entry = Entry.create :title => @title, :content => @content, :rating => @rating
DbType.create
end
end
module SimpleTestMethods
include FixtureSetup
def test_entries_created
assert ActiveRecord::Base.connection.tables.find{|t| t =~ /^entries$/i}, "entries not created"
end
def test_entries_empty
Entry.delete_all
assert_equal 0, Entry.count
end
def test_find_with_string_slug
new_entry = Entry.create(:title => "Blah")
entry = Entry.find(new_entry.to_param)
assert_equal new_entry.id, entry.id
end
def test_insert_returns_id
unless ActiveRecord::Base.connection.adapter_name =~ /oracle/i
value = ActiveRecord::Base.connection.insert("INSERT INTO entries (title, content, rating) VALUES('insert_title', 'some content', 1)")
assert !value.nil?
entry = Entry.find_by_title('insert_title')
assert_equal value, entry.id
end
end
def test_create_new_entry
Entry.delete_all
post = Entry.new
post.title = @title
post.content = @content
post.rating = @rating
post.save
assert_equal 1, Entry.count
end
def test_create_partial_new_entry
new_entry = Entry.create(:title => "Blah")
new_entry2 = Entry.create(:title => "Bloh")
end
def test_find_and_update_entry
post = Entry.find(:first)
assert_equal @title, post.title
assert_equal @content, post.content
assert_equal @rating, post.rating
post.title = @new_title
post.save
post = Entry.find(:first)
assert_equal @new_title, post.title
end
def test_destroy_entry
prev_count = Entry.count
post = Entry.find(:first)
post.destroy
assert_equal prev_count - 1, Entry.count
end
if Time.respond_to?(:zone)
def test_save_time_with_utc
current_zone = Time.zone
default_zone = ActiveRecord::Base.default_timezone
ActiveRecord::Base.default_timezone = Time.zone = :utc
now = Time.now
my_time = Time.local now.year, now.month, now.day, now.hour, now.min, now.sec
m = DbType.create! :sample_datetime => my_time
m.reload
assert_equal my_time, m.sample_datetime
rescue
Time.zone = current_zone
ActiveRecord::Base.default_timezone = default_zone
end
def test_save_time
t = Time.now
#precision will only be expected to the second.
time = Time.local(t.year, t.month, t.day, t.hour, t.min, t.sec)
e = DbType.find(:first)
e.sample_datetime = time
e.save!
e = DbType.find(:first)
assert_equal time.in_time_zone, e.sample_datetime
end
def test_save_date_time
t = Time.now
#precision will only be expected to the second.
time = Time.local(t.year, t.month, t.day, t.hour, t.min, t.sec)
datetime = time.to_datetime
e = DbType.find(:first)
e.sample_datetime = datetime
e.save!
e = DbType.find(:first)
assert_equal time, e.sample_datetime.localtime
end
def test_save_time_with_zone
t = Time.now
#precision will only be expected to the second.
original_time = Time.local(t.year, t.month, t.day, t.hour, t.min, t.sec)
time = original_time.in_time_zone
e = DbType.find(:first)
e.sample_datetime = time
e.save!
e = DbType.find(:first)
assert_equal time, e.sample_datetime
end
end
def test_save_float
e = DbType.find(:first)
e.sample_float = 12.0
e.save!
e = DbType.find(:first)
assert_equal(12.0, e.sample_float)
end
def test_save_date
date = Date.new(2007)
e = DbType.find(:first)
e.sample_date = date
e.save!
e = DbType.find(:first)
if DbType.columns_hash["sample_date"].type == :datetime
# Oracle doesn't distinguish btw date/datetime
assert_equal date, e.sample_date.to_date
else
assert_equal date, e.sample_date
end
end
def test_boolean
# An unset boolean should default to nil
e = DbType.find(:first)
assert_equal(nil, e.sample_boolean)
e.sample_boolean = true
e.save!
e = DbType.find(:first)
assert_equal(true, e.sample_boolean)
end
def test_integer
# An unset boolean should default to nil
e = DbType.find(:first)
assert_equal(nil, e.sample_integer)
e.sample_integer = 10
e.save!
e = DbType.find(:first)
assert_equal(10, e.sample_integer)
end
def test_text
# An unset boolean should default to nil
e = DbType.find(:first)
# Oracle adapter initializes all CLOB fields with empty_clob() function,
# so they all have a initial value of an empty string ''
assert_equal(nil, e.sample_text) unless ActiveRecord::Base.connection.adapter_name =~ /oracle/i
e.sample_text = "ooop"
e.save!
e = DbType.find(:first)
assert_equal("ooop", e.sample_text)
end
def test_string
e = DbType.find(:first)
# An empty string is treated as a null value in Oracle: http://www.techonthenet.com/oracle/questions/empty_null.php
assert_equal('', e.sample_string) unless ActiveRecord::Base.connection.adapter_name =~ /oracle/i
e.sample_string = "ooop"
e.save!
e = DbType.find(:first)
assert_equal("ooop", e.sample_string)
end
def test_save_binary
#string is 60_000 bytes
binary_string = "\000ABCDEFGHIJKLMNOPQRSTUVWXYZ'\001\003"*1#2_000
e = DbType.find(:first)
e.sample_binary = binary_string
e.send(:write_attribute, :binary, binary_string)
e.save!
e = DbType.find(:first)
assert_equal binary_string, e.sample_binary
end
def test_indexes
# Only test indexes if we have implemented it for the particular adapter
if @connection.respond_to?(:indexes)
indexes = @connection.indexes(:entries)
assert_equal(0, indexes.size)
index_name = "entries_index"
@connection.add_index(:entries, :updated_on, :name => index_name)
indexes = @connection.indexes(:entries)
assert_equal(1, indexes.size)
assert_equal "entries", indexes.first.table.to_s
assert_equal index_name, indexes.first.name
assert !indexes.first.unique
assert_equal ["updated_on"], indexes.first.columns
end
end
def test_dumping_schema
require 'active_record/schema_dumper'
@connection.add_index :entries, :title
StringIO.open do |io|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, io)
assert_match(/add_index "entries",/, io.string)
end
@connection.remove_index :entries, :title
end
def test_nil_values
test = AutoId.create('value' => '')
assert_nil AutoId.find(test.id).value
end
def test_invalid
e = Entry.new(:title => @title, :content => @content, :rating => ' ')
assert e.valid?
end
def test_reconnect
assert_equal 1, Entry.count
@connection.reconnect!
assert_equal 1, Entry.count
end
if jruby?
def test_connection_valid
assert_raises(ActiveRecord::ActiveRecordError) do
@connection.raw_connection.with_connection_retry_guard do |c|
begin
stmt = c.createStatement
stmt.execute "bogus sql"
ensure
stmt.close rescue nil
end
end
end
end
class Animal < ActiveRecord::Base; end
# ENEBO: Is this really ar-jdbc-specific or a bug in our adapter?
def test_fetching_columns_for_nonexistent_table_should_raise
assert_raises(ActiveRecord::ActiveRecordError) do
Animal.columns
end
end
end
def test_disconnect
assert_equal 1, Entry.count
ActiveRecord::Base.clear_active_connections!
ActiveRecord::Base.connection_pool.disconnect! if ActiveRecord::Base.respond_to?(:connection_pool)
assert !ActiveRecord::Base.connected?
assert_equal 1, Entry.count
assert ActiveRecord::Base.connected?
end
def test_add_not_null_column_to_table
AddNotNullColumnToTable.up
AddNotNullColumnToTable.down
end
def test_validates_uniqueness_of_strings_case_sensitive
# In MySQL and MsSQL, string cmps are case-insensitive by default, so skip this test
return if ActiveRecord::Base.connection.config[:adapter] =~ /m[sy]sql/
name_lower = ValidatesUniquenessOfString.new(:cs_string => "name", :ci_string => '1')
name_lower.save!
name_upper = ValidatesUniquenessOfString.new(:cs_string => "NAME", :ci_string => '2')
assert_nothing_raised do
name_upper.save!
end
name_lower_collision = ValidatesUniquenessOfString.new(:cs_string => "name", :ci_string => '3')
assert_raise ActiveRecord::RecordInvalid do
name_lower_collision.save!
end
name_upper_collision = ValidatesUniquenessOfString.new(:cs_string => "NAME", :ci_string => '4')
assert_raise ActiveRecord::RecordInvalid do
name_upper_collision.save!
end
end
def test_validates_uniqueness_of_strings_case_insensitive
name_lower = ValidatesUniquenessOfString.new(:cs_string => '1', :ci_string => "name")
name_lower.save!
name_upper = ValidatesUniquenessOfString.new(:cs_string => '2', :ci_string => "NAME")
assert_raise ActiveRecord::RecordInvalid do
name_upper.save!
end
name_lower_collision = ValidatesUniquenessOfString.new(:cs_string => '3', :ci_string => "name")
assert_raise ActiveRecord::RecordInvalid do
name_lower_collision.save!
end
alternate_name_upper = ValidatesUniquenessOfString.new(:cs_string => '4', :ci_string => "ALTERNATE_NAME")
assert_nothing_raised do
alternate_name_upper.save!
end
alternate_name_upper_collision = ValidatesUniquenessOfString.new(:cs_string => '5', :ci_string => "ALTERNATE_NAME")
assert_raise ActiveRecord::RecordInvalid do
alternate_name_upper_collision.save!
end
alternate_name_lower = ValidatesUniquenessOfString.new(:cs_string => '6', :ci_string => "alternate_name")
assert_raise ActiveRecord::RecordInvalid do
alternate_name_lower.save!
end
end
class ChangeEntriesTable < ActiveRecord::Migration
def self.up
change_table :entries do |t|
t.string :author
end if respond_to?(:change_table)
end
def self.down
change_table :entries do |t|
t.remove :author
end if respond_to?(:change_table)
end
end
def test_change_table
ChangeEntriesTable.up
ChangeEntriesTable.down
end
def test_string_id
f = StringId.new
f.id = "some_string"
f.save
f = StringId.first #reload is essential
assert_equal "some_string", f.id
end
end
module MultibyteTestMethods
include MigrationSetup
if defined?(JRUBY_VERSION)
def setup
super
config = ActiveRecord::Base.connection.config
jdbc_driver = ActiveRecord::ConnectionAdapters::JdbcDriver.new(config[:driver])
jdbc_driver.load
@java_con = jdbc_driver.connection(config[:url], config[:username], config[:password])
@java_con.setAutoCommit(true)
end
def teardown
@java_con.close
super
end
def test_select_multibyte_string
@java_con.createStatement().execute("insert into entries (id, title, content) values (1, 'テスト', '本文')")
entry = Entry.find(:first)
assert_equal "テスト", entry.title
assert_equal "本文", entry.content
assert_equal entry, Entry.find_by_title("テスト")
end
def test_update_multibyte_string
Entry.create!(:title => "テスト", :content => "本文")
rs = @java_con.createStatement().executeQuery("select title, content from entries")
assert rs.next
assert_equal "テスト", rs.getString(1)
assert_equal "本文", rs.getString(2)
end
end
def test_multibyte_aliasing
str = "テスト"
quoted_alias = Entry.connection.quote_column_name(str)
sql = "SELECT title AS #{quoted_alias} from entries"
records = Entry.connection.select_all(sql)
records.each do |rec|
rec.keys.each do |key|
assert_equal str, key
end
end
end
def test_chinese_word
chinese_word = '中文'
new_entry = Entry.create(:title => chinese_word)
new_entry.reload
assert_equal chinese_word, new_entry.title
end
end
module NonUTF8EncodingMethods
def setup
@connection = ActiveRecord::Base.remove_connection
latin2_connection = @connection.dup
latin2_connection[:encoding] = 'latin2'
latin2_connection.delete(:url) # pre-gen url gets stashed; remove to re-gen
ActiveRecord::Base.establish_connection latin2_connection
CreateEntries.up
end
def teardown
CreateEntries.down
ActiveRecord::Base.establish_connection @connection
end
def test_nonutf8_encoding_in_entry
prague_district = 'hradčany'
new_entry = Entry.create :title => prague_district
new_entry.reload
assert_equal prague_district, new_entry.title
end
end
module ActiveRecord3TestMethods
def self.included(base)
base.send :include, Tests if ActiveRecord::VERSION::MAJOR == 3
end
module Tests
def test_where
entries = Entry.where(:title => @entry.title)
assert_equal @entry, entries.first
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jdbc_common.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jdbc_common.rb | # Simple method to reduce the boilerplate
def jruby?
defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby"
end
require 'rubygems'
require 'pick_rails_version'
require 'jdbc_adapter' if jruby?
puts "Using activerecord version #{ActiveRecord::VERSION::STRING}"
puts "Specify version with AR_VERSION=={version} or RUBYLIB={path}"
require 'models/auto_id'
require 'models/entry'
require 'models/data_types'
require 'models/add_not_null_column_to_table'
require 'models/validates_uniqueness_of_string'
require 'models/string_id'
require 'simple'
require 'has_many_through'
require 'helper'
require 'test/unit'
# Comment/uncomment to enable logging to be loaded for any of the database adapters
# require 'db/logger'
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/cachedb_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/cachedb_simple_test.rb | require 'jdbc_common'
require 'db/cachedb'
class CacheDBSimpleTest < Test::Unit::TestCase
include SimpleTestMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_info_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_info_test.rb | require 'jdbc_common'
require 'db/mysql'
class DBSetup < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.string :title
end
create_table :cars, :primary_key => 'legacy_id' do |t|
t.string :name
end
create_table :cats, :id => false do |t|
t.string :name
end
end
def self.down
drop_table :books
drop_table :cars
drop_table :cats
end
end
class MysqlInfoTest < Test::Unit::TestCase
def setup
DBSetup.up
@connection = ActiveRecord::Base.connection
end
def teardown
DBSetup.down
end
## primary_key
def test_should_return_the_primary_key_of_a_table
assert_equal 'id', @connection.primary_key('books')
end
def test_should_be_able_to_return_a_custom_primary_key
assert_equal 'legacy_id', @connection.primary_key('cars')
end
def test_should_return_nil_for_a_table_without_a_primary_key
assert_nil @connection.primary_key('cats')
end
## structure_dump
def test_should_include_the_tables_in_a_structure_dump
# TODO: Improve these tests, I added this one because no other tests exists for this method.
dump = @connection.structure_dump
assert dump.include?('CREATE TABLE `books`')
assert dump.include?('CREATE TABLE `cars`')
assert dump.include?('CREATE TABLE `cats`')
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jndi_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jndi_test.rb | # In order to run these tests, you need to have a few things on your
# classpath. First, you're going to need the Sun File system
# context. You can get that here:
#
# http://java.sun.com/products/jndi/serviceproviders.html.
#
# Make sure that you put both the fscontext.jar and the
# providerutil.jar on your classpath.
#
# To support the connection pooling in the test, you'll need
# commons-dbcp, commons-pool, and commons-collections.
#
# Finally, you'll need the jdbc driver, which is derby, for this test.
require 'jdbc_common'
require 'db/jndi_config'
class DerbyJndiTest < Test::Unit::TestCase
include SimpleTestMethods
alias_method :setup_simple, :setup
def setup
ActiveRecord::Base.establish_connection({
:jndi => 'jdbc/derbydb',
:adapter => 'jdbc'})
logger = Logger.new('jndi_test.log')
logger.level = Logger::DEBUG
ActiveRecord::Base.logger = logger
setup_simple
end
end
at_exit {
require 'fileutils'
FileUtils.rm_rf 'derby-testdb'
}
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_legacy_types_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_legacy_types_test.rb | require 'jdbc_common'
require 'db/mssql'
ActiveRecord::Schema.verbose = false
class CreateArticles < ActiveRecord::Migration
def self.up
execute <<-SQL
CREATE TABLE articles (
[id] int NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[title] VARCHAR(100),
[author] VARCHAR(60) DEFAULT 'anonymous',
[body] TEXT
)
SQL
end
def self.down
drop_table "articles"
end
end
class Article < ActiveRecord::Base
end
class MsSQLLegacyTypesTest < Test::Unit::TestCase
def setup
CreateArticles.up
@connection = ActiveRecord::Base.connection
end
def teardown
CreateArticles.down
ActiveRecord::Base.clear_active_connections!
end
def test_varchar_column
Article.create!(:title => "Blah blah")
article = Article.first
assert_equal("Blah blah", article.title)
end
SAMPLE_TEXT = "Lorem ipsum dolor sit amet ..."
def test_text_column
Article.create!(:body => SAMPLE_TEXT)
article = Article.first
assert_equal(SAMPLE_TEXT, article.body)
end
def test_varchar_default_value
assert_equal("anonymous", Article.new.author)
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/derby_multibyte_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/derby_multibyte_test.rb | # To run this script, run the following in a mysql instance:
#
# drop database if exists weblog_development;
# create database weblog_development;
# grant all on weblog_development.* to blog@localhost;
require 'jdbc_common'
require 'db/derby'
class DerbyMultibyteTest < Test::Unit::TestCase
include MultibyteTestMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/helper.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/helper.rb | module Kernel
def find_executable?(name)
ENV['PATH'].split(File::PATH_SEPARATOR).detect {|p| File.executable?(File.join(p, 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_simple_test.rb | require 'jdbc_common'
require 'db/mssql'
class MsSQLSimpleTest < Test::Unit::TestCase
include SimpleTestMethods
# MS SQL 2005 doesn't have a DATE class, only TIMESTAMP.
undef_method :test_save_date
# String comparisons are insensitive by default
undef_method :test_validates_uniqueness_of_strings_case_sensitive
def test_does_not_munge_quoted_strings
example_quoted_values = [%{'quoted'}, %{D'oh!}]
example_quoted_values.each do |value|
entry = Entry.create!(:title => value)
entry.reload
assert_equal(value, entry.title)
end
end
def test_change_column_default
Entry.connection.change_column "entries", "title", :string, :default => "new default"
Entry.reset_column_information
assert_equal("new default", Entry.new.title)
Entry.connection.change_column "entries", "title", :string, :default => nil
Entry.reset_column_information
assert_equal(nil, Entry.new.title)
end
def test_change_column_nullability
Entry.connection.change_column "entries", "title", :string, :null => true
Entry.reset_column_information
title_column = Entry.columns.find { |c| c.name == "title" }
assert(title_column.null)
Entry.connection.change_column "entries", "title", :string, :null => false
Entry.reset_column_information
title_column = Entry.columns.find { |c| c.name == "title" }
assert(!title_column.null)
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/derby_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/derby_simple_test.rb | # To run this script, run the following in a mysql instance:
#
# drop database if exists weblog_development;
# create database weblog_development;
# grant all on weblog_development.* to blog@localhost;
require 'jdbc_common'
require 'db/derby'
class DerbySimpleTest < Test::Unit::TestCase
include SimpleTestMethods
# Check that a table-less VALUES(xxx) query (like SELECT works.
def test_values
value = nil
assert_nothing_raised do
value = ActiveRecord::Base.connection.send(:select_rows, "VALUES('ur', 'doin', 'it', 'right')")
end
assert_equal [['ur', 'doin', 'it', 'right']], value
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_db_create_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mssql_db_create_test.rb | require 'abstract_db_create'
require 'db/mssql'
class MysqlDbCreateTest < Test::Unit::TestCase
include AbstractDbCreate
def db_config
MSSQL_CONFIG
end
def test_rake_db_create
begin
Rake::Task["db:create"].invoke
rescue => e
if e.message =~ /CREATE DATABASE permission denied/
puts "\nwarning: db:create test skipped; add 'dbcreator' role to user '#{db_config[:username]}' to run"
return
end
end
ActiveRecord::Base.establish_connection(db_config.merge(:database => "master"))
select = "SELECT NAME FROM sys.sysdatabases"
select = "SELECT name FROM master..sysdatabases ORDER BY name" if ActiveRecord::Base.connection.sqlserver_version == "2000"
databases = ActiveRecord::Base.connection.select_rows(select).flatten
assert databases.include?(@db_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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_db_create_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/mysql_db_create_test.rb | require 'abstract_db_create'
require 'db/mysql'
class MysqlDbCreateTest < Test::Unit::TestCase
include AbstractDbCreate
def db_config
MYSQL_CONFIG
end
if find_executable?("mysql")
def test_rake_db_create
Rake::Task["db:create"].invoke
output = nil
IO.popen("mysql -u #{MYSQL_CONFIG[:username]} --password=#{MYSQL_CONFIG[:password]}", "r+") do |mysql|
mysql << "show databases where `Database` = '#{@db_name}';"
mysql.close_write
assert mysql.read =~ /#{@db_name}/m
end
end
else
def test_skipped
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_db_create_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_db_create_test.rb | require 'abstract_db_create'
require 'db/postgres'
class PostgresDbCreateTest < Test::Unit::TestCase
include AbstractDbCreate
def db_config
POSTGRES_CONFIG
end
if find_executable?("psql")
def test_rake_db_create
Rake::Task["db:create"].invoke
output = `psql -c '\\l'`
assert output =~ /#{@db_name}/m
end
else
def test_skipped
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db2_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db2_simple_test.rb | require 'jdbc_common'
require 'db/db2'
class DB2SimpleTest < Test::Unit::TestCase
include SimpleTestMethods
end
class DB2HasManyThroughTest < Test::Unit::TestCase
include HasManyThroughMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_simple_test.rb | # To run this script, set up the following postgres user and database:
#
# sudo -u postgres createuser -D -A -P blog
# sudo -u postgres createdb -O blog weblog_development
#
require 'jdbc_common'
require 'db/postgres'
class PostgresSimpleTest < Test::Unit::TestCase
include SimpleTestMethods
include ActiveRecord3TestMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/h2_simple_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/h2_simple_test.rb | require 'jdbc_common'
require 'db/h2'
class H2SimpleTest < Test::Unit::TestCase
include SimpleTestMethods
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_nonseq_pkey_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/postgres_nonseq_pkey_test.rb | require 'rubygems'
require 'active_record'
require 'jdbc_common'
require 'db/postgres'
class CreateUrls < ActiveRecord::Migration
def self.up
create_table 'urls', :id => false do |t|
t.text :uhash, :null => false
t.text :url, :null => false
end
execute "ALTER TABLE urls ADD PRIMARY KEY (uhash)"
end
def self.down
drop_table 'urls'
end
end
class Url < ActiveRecord::Base
set_primary_key :uhash
#Shouldn't be needed: set_sequence_name nil
end
class PostgresNonSeqPKey < Test::Unit::TestCase
def setup
CreateUrls.up
end
def teardown
CreateUrls.down
end
def test_create
url = Url.create! do |u|
u.uhash = 'uhash'
u.url = 'http://url'
end
assert_equal( 'uhash', url.uhash )
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/abstract_db_create.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/abstract_db_create.rb | require 'jdbc_common'
require 'rake'
module Rails
class Configuration
end
class Application
def self.config
@config ||= Object.new
end
end
end
module AbstractDbCreate
def setup
@prevapp = Rake.application
Rake.application = Rake::Application.new
verbose(true)
@prevconfigs = ActiveRecord::Base.configurations
ActiveRecord::Base.connection.disconnect!
@db_name = 'test_rake_db_create'
setup_rails
set_rails_constant("env", "unittest")
set_rails_constant("root", ".")
load File.dirname(__FILE__) + '/../lib/jdbc_adapter/jdbc.rake' if jruby?
task :environment do
ActiveRecord::Base.configurations = configurations
end
task :rails_env
end
def teardown
Rake::Task["db:drop"].invoke
Rake.application = @prevapp
restore_rails
ActiveRecord::Base.configurations = @prevconfigs
ActiveRecord::Base.establish_connection(db_config)
end
def setup_rails
if ActiveRecord::VERSION::MAJOR == 3
setup_rails3
else
setup_rails2
end
end
def configurations
the_db_name = @db_name
the_db_config = db_config
@configs = { "unittest" => the_db_config.merge({:database => the_db_name}).stringify_keys! }
end
def setup_rails2
configs = configurations
Rails::Configuration.class_eval do
define_method(:database_configuration) { configs }
end
ar_version = $LOADED_FEATURES.grep(%r{active_record/version}).first
ar_lib_path = $LOAD_PATH.detect {|p| p if File.exist?File.join(p, ar_version)}
ar_lib_path = ar_lib_path.sub(%r{activerecord/lib}, 'railties/lib') # edge rails
rails_lib_path = ar_lib_path.sub(/activerecord/, 'rails') # gem rails
load "#{rails_lib_path}/tasks/databases.rake"
end
def setup_rails3
configs = configurations
(class << Rails::Application.config; self ; end).instance_eval do
define_method(:database_configuration) { configs }
end
ar_version = $LOADED_FEATURES.grep(%r{active_record/version}).first
ar_lib_path = $LOAD_PATH.detect {|p| p if File.exist?File.join(p, ar_version)}
load "#{ar_lib_path}/active_record/railties/databases.rake"
end
def set_rails_constant(name, value)
cname ="RAILS_#{name.upcase}"
@constants ||= {}
@constants[name] = Object.const_get(cname) rescue nil
silence_warnings { Object.const_set(cname, value) }
Rails.instance_eval do
if instance_methods(false).include?(name)
alias_method "orig_#{name}", name
define_method(name) { value }
end
end
end
def restore_rails
@constants.each do |key,value|
silence_warnings { Object.const_set("RAILS_#{key.upcase}", value) }
Rails.instance_eval do
if instance_methods(false).include?(name)
remove_method name
alias_method name, "orig_#{name}"
end
end
end
end
def silence_warnings
prev, $VERBOSE = $VERBOSE, nil
yield
ensure
$VERBOSE = prev
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testLoadActiveRecord.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testLoadActiveRecord.rb | require 'test/minirunit'
RAILS_CONNECTION_ADAPTERS = ['abstract']
test_load 'active_record'
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testHsqldb.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testHsqldb.rb |
require 'minirunit'
config = {
:adapter => 'jdbc',
:username => 'sa',
:password => '',
:driver => 'org.hsqldb.jdbcDriver',
:url => 'jdbc:hsqldb:test.db'
}
RAILS_CONNECTION_ADAPTERS = ['abstract', 'jdbc']
require 'active_record'
ActiveRecord::Base.establish_connection(config)
require 'logger'
ActiveRecord::Base.logger = Logger.new($stdout)
ActiveRecord::Base.logger.level = Logger::DEBUG
class CreateEntries < ActiveRecord::Migration
def self.up
create_table "entries", :force => true do |t|
t.column :title, :string, :limit => 100
t.column :updated_on, :datetime
t.column :content, :text
end
end
def self.down
drop_table "entries"
end
end
CreateEntries.up
test_ok ActiveRecord::Base.connection.tables.include?('entries')
class Entry < ActiveRecord::Base
end
Entry.delete_all
test_equal 0, Entry.count
TITLE = "First post!"
CONTENT = "Hello from JRuby on Rails!"
NEW_TITLE = "First post updated title"
post = Entry.new
post.title = TITLE
post.content = CONTENT
post.save
test_equal 1, Entry.count
post = Entry.find(:first)
test_equal TITLE, post.title
test_equal CONTENT, post.content
post.title = NEW_TITLE
post.save
post = Entry.find(:first)
test_equal NEW_TITLE, post.title
post.destroy
test_equal 0, Entry.count
CreateEntries.down
# Clean up hsqldb when done
Dir['test.db*'].each {|f| File.delete(f)}
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testConnect.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testConnect.rb | require 'test/minirunit'
RAILS_CONNECTION_ADAPTERS = ['abstract', 'jdbc']
require 'active_record'
connspec = ActiveRecord::Base.establish_connection(
:adapter => 'jdbc',
:driver => 'com.mysql.jdbc.Driver',
:url => 'jdbc:mysql://localhost:3306/test',
:username => 'rlsmgr',
:password => ''
)
puts "#{connspec}"
puts "#{ActiveRecord::Base.connection}"
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testRawSelect.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testRawSelect.rb |
require 'test/minirunit'
RAILS_CONNECTION_ADAPTERS = ['abstract', 'jdbc']
require 'active_record'
connspec = ActiveRecord::Base.establish_connection(
:adapter => 'jdbc',
:driver => 'com.mysql.jdbc.Driver',
:url => 'jdbc:mysql://localhost:3306/weblog_development',
:username => 'blog',
:password => ''
)
connection = ActiveRecord::Base.connection
results = connection.execute "select * from entries"
test_equal results.length, 1
row = results.first
test_equal 'First post', row['title']
test_equal 'First post d00d!', row['content']
puts row.inspect
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testMysql.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testMysql.rb | # To run this script, run the following in a mysql instance:
#
# drop database if exists weblog_development;
# create database weblog_development;
# grant all on weblog_development.* to blog@localhost;
require 'minirunit'
config = {
:username => 'blog',
:password => ''
}
if RUBY_PLATFORM =~ /java/
RAILS_CONNECTION_ADAPTERS = ['abstract', 'jdbc']
config.update({
:adapter => 'jdbc',
:driver => 'com.mysql.jdbc.Driver',
:url => 'jdbc:mysql://localhost:3306/weblog_development',
})
else
config.update({
:adapter => 'mysql',
:database => 'weblog_development',
:host => 'localhost'
})
end
require 'active_record'
ActiveRecord::Base.establish_connection(config)
class CreateEntries < ActiveRecord::Migration
def self.up
create_table "entries", :force => true do |t|
t.column :title, :string, :limit => 100
t.column :updated_on, :datetime
t.column :content, :text
end
end
def self.down
drop_table "entries"
end
end
CreateEntries.up
test_ok ActiveRecord::Base.connection.tables.include?('entries')
class Entry < ActiveRecord::Base
end
Entry.delete_all
test_equal 0, Entry.count
TITLE = "First post!"
CONTENT = "Hello from JRuby on Rails!"
NEW_TITLE = "First post updated title"
post = Entry.new
post.title = TITLE
post.content = CONTENT
post.save
test_equal 1, Entry.count
post = Entry.find(:first)
test_equal TITLE, post.title
test_equal CONTENT, post.content
post.title = NEW_TITLE
post.save
post = Entry.find(:first)
test_equal NEW_TITLE, post.title
post.destroy
test_equal 0, Entry.count
CreateEntries.down
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testH2.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/minirunit/testH2.rb |
require 'minirunit'
config = {
:adapter => 'jdbc',
:username => 'sa',
:password => '',
:driver => 'org.h2.Driver',
:url => 'jdbc:h2:test.db'
}
RAILS_CONNECTION_ADAPTERS = ['abstract', 'jdbc']
require 'active_record'
ActiveRecord::Base.establish_connection(config)
require 'logger'
ActiveRecord::Base.logger = Logger.new($stdout)
ActiveRecord::Base.logger.level = Logger::DEBUG
class CreateEntries < ActiveRecord::Migration
def self.up
create_table "entries", :force => true do |t|
t.column :title, :string, :limit => 100
t.column :updated_on, :datetime
t.column :content, :text
end
end
def self.down
drop_table "entries"
end
end
CreateEntries.up
test_ok ActiveRecord::Base.connection.tables.include?('entries')
class Entry < ActiveRecord::Base
end
Entry.delete_all
test_equal 0, Entry.count
TITLE = "First post!"
CONTENT = "Hello from JRuby on Rails!"
NEW_TITLE = "First post updated title"
post = Entry.new
post.title = TITLE
post.content = CONTENT
post.save
test_equal 1, Entry.count
post = Entry.find(:first)
test_equal TITLE, post.title
test_equal CONTENT, post.content
post.title = NEW_TITLE
post.save
post = Entry.find(:first)
test_equal NEW_TITLE, post.title
post.destroy
test_equal 0, Entry.count
CreateEntries.down
# Clean up hsqldb when done
Dir['test.db*'].each {|f| File.delete(f)}
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/activerecord/connections/native_jdbc_mysql/connection.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/activerecord/connections/native_jdbc_mysql/connection.rb | print "Using native JDBC (MySQL)\n"
require_dependency 'fixtures/course'
require 'logger'
RAILS_CONNECTION_ADAPTERS << 'jdbc'
require "active_record/connection_adapters/jdbc_adapter"
ActiveRecord::Base.logger = Logger.new("debug.log")
db1 = 'activerecord_unittest'
db2 = 'activerecord_unittest2'
ActiveRecord::Base.establish_connection(
:adapter => "jdbc",
:driver => "com.mysql.jdbc.Driver",
:url => "jdbc:mysql://localhost:3306/#{db1}",
:username => "rails"
)
Course.establish_connection(
:adapter => "jdbc",
:driver => "com.mysql.jdbc.Driver",
:url => "jdbc:mysql://localhost:3306/#{db2}",
:username => "rails"
)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/activerecord/connection_adapters/type_conversion_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/activerecord/connection_adapters/type_conversion_test.rb | require 'java'
require 'models/data_types'
require 'active_record/connection_adapters/jdbc_adapter'
require 'db/derby'
require 'test/unit'
JInteger = java.lang.Integer
class TypeConversionTest < Test::Unit::TestCase
TEST_TIME = Time.at(1169964202).gmtime
def setup
DbTypeMigration.up
DbType.create(
:sample_timestamp => TEST_TIME,
:sample_decimal => JInteger::MAX_VALUE + 1)
end
def teardown
DbTypeMigration.down
end
def test_timestamp
types = DbType.find(:first)
assert_equal TEST_TIME, types.sample_timestamp.getutc
end
def test_decimal
types = DbType.find(:first)
assert_equal((JInteger::MAX_VALUE + 1), types.sample_decimal)
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jdbc_adapter/jdbc_db2_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jdbc_adapter/jdbc_db2_test.rb | require 'java'
require 'lib/jdbc_adapter/jdbc_db2'
require 'test/unit'
class JdbcSpec::DB2Test < Test::Unit::TestCase
def setup
@inst = Object.new
@inst.extend JdbcSpec::DB2
@column = Object.new
class <<@column
attr_accessor :type
end
end
def test_quote_decimal
assert_equal %q{'123.45'}, @inst.quote("123.45")
@column.type = :decimal
assert_equal %q{123.45}, @inst.quote("123.45", @column), "decimal columns should not have quotes"
end
def test_primary_key_generation
@column.type = :primary_key
assert_equal 'int not null generated by default as identity (start with 1) primary key', @inst.modify_types({:string => {}, :integer => {}, :boolean => {}})[:primary_key]
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jdbc_adapter/jdbc_sybase_test.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/jdbc_adapter/jdbc_sybase_test.rb | require 'jdbc_common'
require 'jdbc_adapter'
class MockConnection
def adapter=( adapt )
end
end
module ActiveRecord
module ConnectionAdapters
class SybaseAdapterSelectionTest < Test::Unit::TestCase
def testJtdsSelectionUsingDialect()
config = {
:driver => 'net.sourceforge.jtds.Driver',
:dialect => 'sybase'
}
adapt = JdbcAdapter.new(MockConnection.new, nil, config)
assert adapt.kind_of?(JdbcSpec::Sybase), "Should be a sybase adapter"
end
def testJtdsSelectionNotUsingDialect
config = { :driver => 'net.sourceforge.jtds.Driver' }
adapt = JdbcAdapter.new(MockConnection.new, nil, config)
assert adapt.kind_of?(JdbcSpec::MsSQL), "Should be a MsSQL apdater"
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/mysql.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/mysql.rb | MYSQL_CONFIG = {
:username => 'blog',
:password => '',
:adapter => 'mysql',
:database => 'weblog_development',
:host => 'localhost'
}
ActiveRecord::Base.establish_connection(MYSQL_CONFIG)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/cachedb.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/cachedb.rb | config = {
:username => '_SYSTEM',
:password => 'SYS',
:adapter => 'cachedb',
:host => ENV[ "CACHE_HOST" ] || 'localhost',
:database => ENV[ "CACHE_NAMESPACE" ] || 'weblog_development'
}
ActiveRecord::Base.establish_connection( config )
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/logger.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/logger.rb | require 'logger'
ActiveRecord::Base.logger = Logger.new($stdout)
ActiveRecord::Base.logger.level = Logger::DEBUG
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/postgres.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/postgres.rb | POSTGRES_CONFIG = {
:adapter => 'postgresql',
:database => 'weblog_development',
:host => 'localhost',
:username => 'blog',
:password => ''
}
ActiveRecord::Base.establish_connection(POSTGRES_CONFIG)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/jndi_config.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/jndi_config.rb | require 'fileutils'
require 'active_record/connection_adapters/jdbc_adapter'
System = java.lang.System
Context = javax.naming.Context
InitialContext = javax.naming.InitialContext
Reference = javax.naming.Reference
StringRefAddr = javax.naming.StringRefAddr
System.set_property(Context::INITIAL_CONTEXT_FACTORY,
'com.sun.jndi.fscontext.RefFSContextFactory')
project_path = File.expand_path(File.dirname(__FILE__) + '/../..')
jndi_dir = project_path + '/jndi_test'
jdbc_dir = jndi_dir + '/jdbc'
FileUtils.mkdir_p jdbc_dir unless File.exist?(jdbc_dir)
System.set_property(Context::PROVIDER_URL, "file://#{jndi_dir}")
derby_ref = Reference.new('javax.sql.DataSource',
'org.apache.commons.dbcp.BasicDataSourceFactory',
nil)
derby_ref.add StringRefAddr.new('driverClassName',
'org.apache.derby.jdbc.EmbeddedDriver')
derby_ref.add StringRefAddr.new('url',
'jdbc:derby:derby-testdb;create=true')
derby_ref.add StringRefAddr.new('username', 'sa')
derby_ref.add StringRefAddr.new('password', '')
ic = InitialContext.new
ic.rebind("jdbc/derbydb", derby_ref)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/oracle.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/oracle.rb | config = {
:username => 'blog',
:password => 'blog',
:adapter => 'oracle',
:host => ENV["ORACLE_HOST"] || 'localhost',
:database => ENV["ORACLE_SID"] || 'XE' # XE is the default SID for oracle xe
}
ActiveRecord::Base.establish_connection(config)
# Here are some notes of things I had to do to get running on Oracle
# XE.
#
# ON Linux:
# create tablespace weblog_development
# datafile '/usr/lib/oracle/xe/oradata/XE/weblog_development.dbf';
# ON Windows XP:
# create tablespace weblog_development
# datafile 'C:\ORACLEXE\ORADATA\XE\WEBLOGD.DBF' size 16m;
#
# create user blog identified by blog
# default tablespace weblog_development;
# grant all privileges to blog;
#
# You might need to up the number of processes and restart the
# listener. (In my case, I had to reboot.) See
# http://it.newinstance.it/2007/06/01/ora-12519-tnsno-appropriate-service-handler-found/
#
# alter system set PROCESSES=150 scope=SPFILE;
#
# These might be helpful too (numbers are rather arbitrary...)
#
# alter system set TRANSACTIONS=126 scope=SPFILE;
# alter system set SESSIONS=115 scope=SPFILE;
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/db2.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/db2.rb | config = {
:username => "blog",
:password => "",
:adapter => "jdbc",
:driver => "com.ibm.db2.jcc.DB2Driver",
:url => "jdbc:db2:weblog_development"
}
ActiveRecord::Base.establish_connection(config)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/hsqldb.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/hsqldb.rb | config = {
:adapter => 'hsqldb',
:database => 'test.db'
}
ActiveRecord::Base.establish_connection(config)
at_exit {
# Clean up hsqldb when done
Dir['test.db*'].each {|f| File.delete(f)}
File.delete('hsqldb-testdb.log') rescue nil #can't delete on windows
}
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/mssql.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/mssql.rb | MSSQL_CONFIG = {
:username => 'blog',
:password => '',
:adapter => 'mssql',
:database => 'weblog_development'
}
MSSQL_CONFIG[:host] = ENV['SQLHOST'] if ENV['SQLHOST']
ActiveRecord::Base.establish_connection(MSSQL_CONFIG)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/derby.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/derby.rb | require 'logger'
config = {
:adapter => 'derby',
:database => "derby-testdb"
}
ActiveRecord::Base.establish_connection(config)
at_exit {
# Clean up derby files
require 'fileutils'
FileUtils.rm_rf('derby-testdb')
}
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/h2.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/h2.rb | config = {
:adapter => 'h2',
:database => 'test.db'
}
ActiveRecord::Base.establish_connection(config)
at_exit {
# Clean up hsqldb when done
Dir['test.db*'].each {|f| File.delete(f)}
}
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/jdbc.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/jdbc.rb | require 'jdbc/mysql'
config = {
:username => 'blog',
:password => '',
:adapter => 'jdbc',
:driver => 'com.mysql.jdbc.Driver',
:url => 'jdbc:mysql://localhost:3306/weblog_development'
}
ActiveRecord::Base.establish_connection(config)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/informix.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/informix.rb | config = {
:username => 'blog',
:password => 'blog',
:adapter => 'informix',
:servername => 'ol_weblog',
:database => 'weblog_development',
:host => 'localhost',
:port => '9088'
}
ActiveRecord::Base.establish_connection(config)
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/sqlite3.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/db/sqlite3.rb | require 'jdbc/sqlite3' if jruby?
config = {
:adapter => jruby? ? 'jdbcsqlite3' : 'sqlite3',
:dbfile => 'test.sqlite3.db'
# :url => 'jdbc:sqlite:test.sqlite3.db',
# :driver => 'org.sqlite.JDBC'
}
ActiveRecord::Base.establish_connection(config)
at_exit {
# Clean up sqlite3 db when done
Dir['test.sqlite3*'].each {|f| File.delete(f)}
}
| 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/entry.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/entry.rb | require 'rubygems'
require 'active_record'
class CreateEntries < ActiveRecord::Migration
def self.up
create_table "entries", :force => true do |t|
t.column :title, :string, :limit => 100
t.column :updated_on, :datetime
t.column :content, :text
t.column :rating, :decimal, :precision => 10, :scale => 2
end
end
def self.down
drop_table "entries"
end
end
class Entry < ActiveRecord::Base
def to_param
"#{id}-#{title.gsub(/[^a-zA-Z0-9]/, '-')}"
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/data_types.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/data_types.rb | require 'rubygems'
require 'active_record'
class DbTypeMigration < ActiveRecord::Migration
def self.up
create_table "db_types", :force => true do |t|
t.column :sample_timestamp, :timestamp
t.column :sample_datetime, :datetime
t.column :sample_date, :date
t.column :sample_time, :time
t.column :sample_decimal, :decimal, :precision => 15, :scale => 0
t.column :sample_small_decimal, :decimal, :precision => 3, :scale => 2
t.column :sample_float, :float
t.column :sample_binary, :binary
t.column :sample_boolean, :boolean
t.column :sample_string, :string, :default => ''
t.column :sample_integer, :integer, :limit => 5
t.column :sample_text, :text
end
end
def self.down
drop_table "db_types"
end
end
class DbType < ActiveRecord::Base
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/reserved_word.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/reserved_word.rb | require 'rubygems'
require 'active_record'
class CreateReservedWords < ActiveRecord::Migration
def self.up
create_table "reserved_words", :force => true do |t|
t.column :position, :integer
t.column :select, :integer
end
end
def self.down
drop_table "reserved_words"
end
end
class ReservedWord < ActiveRecord::Base
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/auto_id.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/auto_id.rb | require 'rubygems'
require 'active_record'
class CreateAutoIds < ActiveRecord::Migration
def self.up
create_table "auto_ids", :force => true do |t|
t.column :value, :integer
end
end
def self.down
drop_table "auto_ids"
end
end
class AutoId < ActiveRecord::Base
def self.table_name () "auto_ids" 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/add_not_null_column_to_table.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/add_not_null_column_to_table.rb | require 'rubygems'
require 'active_record'
class AddNotNullColumnToTable < ActiveRecord::Migration
def self.up
add_column :entries, :color, :string, :null => false, :default => "blue"
end
def self.down
remove_column :entries, :color
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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/string_id.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/string_id.rb | require 'rubygems'
require 'active_record'
class CreateStringIds < ActiveRecord::Migration
def self.up
create_table "string_ids", :force => true, :id => false do |t|
t.string :id
end
end
def self.down
drop_table "string_ids"
end
end
class StringId < ActiveRecord::Base
def self.table_name () "string_ids" 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/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/mixed_case.rb | tools/jruby-1.5.1/lib/ruby/gems/1.8/gems/activerecord-jdbc-adapter-0.9.7-java/test/models/mixed_case.rb | require 'rubygems'
require 'active_record'
module Migration
class MixedCase < ActiveRecord::Migration
def self.up
create_table "mixed_cases" do |t|
t.column :SOME_value, :string
end
end
def self.down
drop_table "mixed_cases"
end
end
end
class MixedCase < ActiveRecord::Base
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.