repo
string
commit
string
message
string
diff
string
kameeoze/jruby-poi
523b83ec37989ccb617791660fa3b6c89d6286fa
Version bump to 0.8.1
diff --git a/VERSION b/VERSION index 8adc70f..c18d72b 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.8.0 \ No newline at end of file +0.8.1 \ No newline at end of file
kameeoze/jruby-poi
5f9418b98ead41fc938a0d11993ccab07c548988
Some more housecleaning. Should be 0.8.0 ready
diff --git a/Rakefile b/Rakefile index adf2782..44c375b 100644 --- a/Rakefile +++ b/Rakefile @@ -1,33 +1,29 @@ -require 'bundler/setup' -require 'rspec/core/rake_task' - +require 'rubygems' +require 'bundler' begin - require 'jeweler' - - Jeweler::Tasks.new do |gemspec| - gemspec.name = "jruby-poi" - gemspec.summary = "Apache POI class library for jruby" - gemspec.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." - gemspec.email = ["[email protected]", "[email protected]"] - gemspec.homepage = "http://github.com/kameeoze/jruby-poi" - gemspec.authors = ["Scott Deming", "Jason Rogers"] - end -rescue LoadError - puts "Jeweler not available. Install it with: gem install jeweler" + Bundler.setup(:default, :development) +rescue Bundler::BundlerError => e + $stderr.puts e.message + $stderr.puts "Run `bundle install` to install missing gems" + exit e.status_code end +require 'rake' -begin - task :default => :spec - desc "Run all examples" - RSpec::Core::RakeTask.new(:spec) +require 'jeweler' +Jeweler::Tasks.new do |gemspec| + gemspec.name = "jruby-poi" + gemspec.summary = "Apache POI class library for jruby" + gemspec.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." + gemspec.license = "Apache" + gemspec.email = ["[email protected]", "[email protected]"] + gemspec.homepage = "http://github.com/kameeoze/jruby-poi" + gemspec.authors = ["Scott Deming", "Jason Rogers"] +end - desc "Run all examples with rcov" - RSpec::Core::RakeTask.new(:coverage) do |t| - t.rcov = true - t.rcov_opts = ['--include', '/lib/', '--exclude', '/gems/,/^specs/,/^.eval.$/'] - end -rescue - puts $!.message - puts "RCov not available. Install it with: gem install rcov (--no-rdoc --no-ri)" +require 'rspec/core' +require 'rspec/core/rake_task' +RSpec::Core::RakeTask.new(:spec) +RSpec::Core::RakeTask.new(:rcov) do |spec| + spec.rcov = true end
kameeoze/jruby-poi
0f96fac128c56570dacb243d02ba0798d717d094
Housekeeping
diff --git a/spec/facade_spec.rb b/spec/facade_spec.rb index 970cd38..d331dac 100644 --- a/spec/facade_spec.rb +++ b/spec/facade_spec.rb @@ -1,46 +1,48 @@ +require 'spec_helper' + describe "POI.Facade" do it "should create specialized methods for boolean methods, getters, and setters" do book = POI::Workbook.create('foo.xlsx') sheet = book.create_sheet sheet.respond_to?(:column_broken?).should be_true sheet.respond_to?(:column_hidden?).should be_true sheet.respond_to?(:display_formulas?).should be_true sheet.respond_to?(:display_gridlines?).should be_true sheet.respond_to?(:selected?).should be_true sheet.respond_to?(:column_breaks).should be_true sheet.respond_to?(:column_break=).should be_true sheet.respond_to?(:autobreaks?).should be_true sheet.respond_to?(:autobreaks=).should be_true sheet.respond_to?(:autobreaks!).should be_true sheet.respond_to?(:column_broken?).should be_true sheet.respond_to?(:fit_to_page).should be_true sheet.respond_to?(:fit_to_page?).should be_true sheet.respond_to?(:fit_to_page=).should be_true sheet.respond_to?(:fit_to_page!).should be_true sheet.respond_to?(:array_formula).should_not be_true sheet.respond_to?(:array_formula=).should_not be_true row = sheet[0] row.respond_to?(:first_cell_num).should be_true row.respond_to?(:height).should be_true row.respond_to?(:height=).should be_true row.respond_to?(:height_in_points).should be_true row.respond_to?(:height_in_points=).should be_true row.respond_to?(:zero_height?).should be_true row.respond_to?(:zero_height!).should be_true row.respond_to?(:zero_height=).should be_true cell = row[0] cell.respond_to?(:boolean_cell_value).should be_true cell.respond_to?(:boolean_cell_value?).should be_true cell.respond_to?(:cached_formula_result_type).should be_true cell.respond_to?(:cell_error_value=).should be_true cell.respond_to?(:cell_value=).should be_true cell.respond_to?(:hyperlink=).should be_true cell.respond_to?(:cell_value!).should be_true cell.respond_to?(:remove_cell_comment!).should be_true cell.respond_to?(:cell_style).should be_true cell.respond_to?(:cell_style=).should be_true end end diff --git a/spec/io_spec.rb b/spec/io_spec.rb index c022c3b..2c91b18 100644 --- a/spec/io_spec.rb +++ b/spec/io_spec.rb @@ -1,67 +1,69 @@ +require 'spec_helper' + describe POI::Workbook do before :each do @mock_output_stream = nil class POI::Workbook def mock_output_stream name @mock_output_stream ||= Java::jrubypoi.MockOutputStream.new name @mock_output_stream end alias_method :original_output_stream, :output_stream unless method_defined?(:original_output_stream) alias_method :output_stream, :mock_output_stream end end after :each do @mock_output_stream = nil class POI::Workbook alias_method :output_stream, :original_output_stream end end it "should read an xlsx file" do name = TestDataFile.expand_path("various_samples.xlsx") book = nil lambda { book = POI::Workbook.open(name) }.should_not raise_exception book.should be_kind_of POI::Workbook end it "should read an xls file" do name = TestDataFile.expand_path("simple_with_picture.xls") book = nil lambda { book = POI::Workbook.open(name) }.should_not raise_exception book.should be_kind_of POI::Workbook end it "should read an ods file", :unimplemented => true do name = TestDataFile.expand_path("spreadsheet.ods") book = nil lambda { book = POI::Workbook.open(name) }.should_not raise_exception book.should be_kind_of POI::Workbook end it "should write an open workbook" do name = TestDataFile.expand_path("various_samples.xlsx") POI::Workbook.open(name) do |book| lambda { book.save }.should_not raise_exception verify_mock_output_stream book.instance_variable_get("@mock_output_stream"), name end end it "should write an open workbook to a new file" do name = TestDataFile.expand_path("various_samples.xlsx") new_name = TestDataFile.expand_path("saved-as.xlsx") POI::Workbook.open(name) do |book| @mock_output_stream.should be_nil lambda { book.save_as(new_name) }.should_not raise_exception verify_mock_output_stream book.instance_variable_get("@mock_output_stream"), new_name end end def verify_mock_output_stream mock_output_stream, name mock_output_stream.should_not be_nil name.should == mock_output_stream.name true.should == mock_output_stream.write_called end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 5e19c22..2c1c18c 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,15 +1,16 @@ -$stderr.puts "included spec_helper.rb" +require 'spec_helper' + RSpec.configure do |c| c.filter_run_excluding :unimplemented => true end require File.expand_path('../lib/poi', File.dirname(__FILE__)) Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f} require File.join(File.dirname(__FILE__), "support", "java", "support.jar") class TestDataFile def self.expand_path(name) File.expand_path(File.join(File.dirname(__FILE__), 'data', name)) end end diff --git a/spec/workbook_spec.rb b/spec/workbook_spec.rb index 166f314..e816f27 100644 --- a/spec/workbook_spec.rb +++ b/spec/workbook_spec.rb @@ -1,369 +1,370 @@ require 'spec_helper' + require 'date' require 'stringio' describe POI::Workbook do it "should open a workbook and allow access to its worksheets" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets.size.should == 5 book.filename.should == name end it "should be able to create a Workbook from an IO object" do content = StringIO.new(open(TestDataFile.expand_path("various_samples.xlsx"), 'rb'){|f| f.read}) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should be able to create a Workbook from a Java input stream" do content = java.io.FileInputStream.new(TestDataFile.expand_path("various_samples.xlsx")) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should return a column of cells by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} end it "should return cells by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.cell("numbers!A1").value.should == 'NUM' book.cell("numbers!A2").to_s.should == '1.0' book.cell("numbers!A3").to_s.should == '2.0' book.cell("numbers!A4").to_s.should == '3.0' book.cell("numbers!A10").to_s.should == '9.0' book.cell("numbers!B10").to_s.should == '81.0' book.cell("numbers!C10").to_s.should == '729.0' book.cell("numbers!D10").to_s.should == '3.0' book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' book.cell("bools & errors!B3").value.should == true book.cell("high refs!AM619").value.should == 'This is some text' book.cell("high refs!AO624").value.should == 24.0 book.cell("high refs!AP631").value.should == 13.0 book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' book.cell(%Q{'bools & errors'!B3}).value.should == true book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' book.cell(%Q{'high refs'!AO624}).value.should == 24.0 book.cell(%Q{'high refs'!AP631}).value.should == 13.0 end it "should handle named cell ranges" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.named_ranges.length.should == 3 book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] book['four_times_six'].should == 24.0 book['nums'].should == (1..13).collect{|e| e * 1.0} # NAMES is a range of empty cells book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] book.cell('NAMES').each do | cell | cell.value.should be_nil cell.poi_cell.should_not be_nil cell.to_s.should be_empty end end it "should return an array of cell values by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book['dates!A2:A16'].should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a end it "should return cell values by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' book['bools & errors!B3'].should == true book['high refs!AM619'].should == 'This is some text' book['high refs!AO624'].should == 24.0 book['high refs!AP631'].should == 13.0 end end describe POI::Worksheets do it "should allow indexing worksheets by ordinal" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets[0].name.should == "text & pic" book.worksheets[1].name.should == "numbers" book.worksheets[2].name.should == "dates" book.worksheets[3].name.should == "bools & errors" end it "should allow indexing worksheets by name" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets["text & pic"].name.should == "text & pic" book.worksheets["numbers"].name.should == "numbers" book.worksheets["dates"].name.should == "dates" end it "should be enumerable" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets.should be_kind_of Enumerable book.worksheets.each do |sheet| sheet.should be_kind_of POI::Worksheet end book.worksheets.size.should == 5 book.worksheets.collect.size.should == 5 end it "returns cells when passing a cell reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book['dates']['A2'].to_s.should == '2010-02-28' book['dates']['a2'].to_s.should == '2010-02-28' book['dates']['B2'].to_s.should == '2010-03-14' book['dates']['b2'].to_s.should == '2010-03-14' book['dates']['C2'].to_s.should == '2010-03-28' book['dates']['c2'].to_s.should == '2010-03-28' end end describe POI::Rows do it "should be enumerable" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) sheet = book.worksheets["text & pic"] sheet.rows.should be_kind_of Enumerable sheet.rows.each do |row| row.should be_kind_of POI::Row end sheet.rows.size.should == 7 sheet.rows.collect.size.should == 7 end end describe POI::Cells do before :each do @name = TestDataFile.expand_path("various_samples.xlsx") @book = POI::Workbook.open(@name) end def book @book end def name @name end it "should be enumerable" do sheet = book.worksheets["text & pic"] rows = sheet.rows cells = rows[0].cells cells.should be_kind_of Enumerable cells.size.should == 1 cells.collect.size.should == 1 end end describe POI::Cell do before :each do @name = TestDataFile.expand_path("various_samples.xlsx") @book = POI::Workbook.open(@name) end def book @book end def name @name end it "should provide dates for date cells" do sheet = book.worksheets["dates"] rows = sheet.rows dates_by_column = [ (Date.parse('2010-02-28')..Date.parse('2010-03-14')), (Date.parse('2010-03-14')..Date.parse('2010-03-28')), (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] (0..2).each do |col| dates_by_column[col].each_with_index do |date, index| row = index + 1 rows[row][col].value.should equal_at_cell(date, row, col) end end end it "should provide numbers for numeric cells" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].value.should equal_at_cell(number, row, 0) rows[row][1].value.should equal_at_cell(number ** 2, row, 1) rows[row][2].value.should equal_at_cell(number ** 3, row, 2) rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) end rows[9][0].to_s.should == '9.0' rows[9][1].to_s.should == '81.0' rows[9][2].to_s.should == '729.0' rows[9][3].to_s.should == '3.0' end it "should handle array access from the workbook down to cells" do book[1][9][0].to_s.should == '9.0' book[1][9][1].to_s.should == '81.0' book[1][9][2].to_s.should == '729.0' book[1][9][3].to_s.should == '3.0' book["numbers"][9][0].to_s.should == '9.0' book["numbers"][9][1].to_s.should == '81.0' book["numbers"][9][2].to_s.should == '729.0' book["numbers"][9][3].to_s.should == '3.0' end it "should provide error text for error cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' rows[6][0].error_value.should be_nil rows[7][0].value.should be_nil rows[7][0].error_value.should == '#DIV/0!' rows[8][0].value.should be_nil rows[8][0].error_value.should == '#N/A' rows[9][0].value.should be_nil rows[9][0].error_value.should == '#NAME?' rows[10][0].value.should be_nil rows[10][0].error_value.should == '#NULL!' rows[11][0].value.should be_nil rows[11][0].error_value.should == '#NUM!' rows[12][0].value.should be_nil rows[12][0].error_value.should == '#REF!' rows[13][0].value.should be_nil rows[13][0].error_value.should == '#VALUE!' lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' rows[7][0].to_s.should == '' #'#DIV/0!' rows[8][0].to_s.should == '' #'#N/A' rows[9][0].to_s.should == '' #'#NAME?' rows[10][0].to_s.should == '' #'#NULL!' rows[11][0].to_s.should == '' #'#NUM!' rows[12][0].to_s.should == '' #'#REF!' rows[13][0].to_s.should == '' #'#VALUE!' rows[14][0].to_s.should == '' end it "should provide booleans for boolean cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].value.should == false rows[1][0].to_s.should == 'false' rows[1][1].value.should == false rows[1][1].to_s.should == 'false' rows[2][0].value.should == true rows[2][0].to_s.should == 'true' rows[2][1].value.should == true rows[2][1].to_s.should == 'true' end it "should provide the cell value as a string" do sheet = book.worksheets["text & pic"] rows = sheet.rows rows[0][0].value.should == "This" rows[1][0].value.should == "is" rows[2][0].value.should == "an" rows[3][0].value.should == "Excel" rows[4][0].value.should == "XLSX" rows[5][0].value.should == "workbook" rows[9][0].value.should == 'This is an Excel XLSX workbook.' rows[0][0].to_s.should == "This" rows[1][0].to_s.should == "is" rows[2][0].to_s.should == "an" rows[3][0].to_s.should == "Excel" rows[4][0].to_s.should == "XLSX" rows[5][0].to_s.should == "workbook" rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' end it "should provide formulas instead of string-ified values" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].to_s(false).should == "#{number}.0" rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" end sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].to_s(false).should == '1=2' rows[1][1].to_s(false).should == 'FALSE' rows[2][0].to_s(false).should == '1=1' rows[2][1].to_s(false).should == 'TRUE' rows[14][0].to_s(false).should == 'foobar(1)' sheet = book.worksheets["text & pic"] sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' end it "should handle getting values out of 'non-existent' cells" do sheet = book.worksheets["bools & errors"] sheet.rows[14][2].value.should be_nil end it "should notify the workbook that I have been updated" do book['dates!A10'].to_s.should == '2010-03-08' book['dates!A16'].to_s.should == '2010-03-14' book['dates!B2'].to_s.should == '2010-03-14' cell = book.cell('dates!B2') cell.formula.should == 'A16' cell.formula = 'A10 + 1' book.cell('dates!B2').poi_cell.should === cell.poi_cell book.cell('dates!B2').formula.should == 'A10 + 1' book['dates!B2'].to_s.should == '2010-03-09' end end diff --git a/spec/writing_spec.rb b/spec/writing_spec.rb index 281b0af..a31a593 100644 --- a/spec/writing_spec.rb +++ b/spec/writing_spec.rb @@ -1,144 +1,146 @@ +require 'spec_helper' + require 'date' require 'stringio' describe "writing Workbooks" do it "should create a new empty workbook" do name = 'new-workbook.xlsx' book = POI::Workbook.create(name) book.should_not be_nil end it "should create a new workbook and write something to it" do name = "spec/data/timesheet-#{Time.now.strftime('%Y%m%d%H%M%S%s')}.xlsx" create_timesheet_spreadsheet(name) book = POI::Workbook.open(name) book.worksheets.size.should == 1 book.worksheets[0].name.should == 'Timesheet' book.filename.should == name book['Timesheet!A3'].should == 'Yegor Kozlov' book.cell('Timesheet!J13').formula_value.should == 'SUM(J3:J12)' FileUtils.rm_f name end def create_timesheet_spreadsheet name='spec/data/timesheet.xlsx' titles = ["Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Total\nHrs", "Overtime\nHrs", "Regular\nHrs"] sample_data = [ ["Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0], ["Gisella Bronzetti", "GB", 4.0, 3.0, 1.0, 3.5, nil, nil, 4.0] ] book = POI::Workbook.create(name) title_style = book.create_style :font_height_in_points => 18, :boldweight => :boldweight_bold, :alignment => :align_center, :vertical_alignment => :vertical_center header_style = book.create_style :font_height_in_points => 11, :color => :white, :fill_foreground_color => :grey_50_percent, :fill_pattern => :solid_foreground, :alignment => :align_center, :vertical_alignment => :vertical_center cell_style = book.create_style :alignment => :align_center, :border_bottom => :border_thin, :border_top => :border_thin, :border_left => :border_thin, :border_right => :border_thin, :bottom_border_color => :black, :right_border_color => :black, :left_border_color => :black, :top_border_color => :black form1_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_25_percent, :alignment => :align_center, :vertical_alignment => :vertical_center form2_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_40_percent, :alignment => :align_center, :vertical_alignment => :vertical_center sheet = book.create_sheet 'Timesheet' print_setup = sheet.print_setup print_setup.landscape = true sheet.fit_to_page = true sheet.horizontally_center = true title_row = sheet.rows[0] title_row.height_in_points = 45 title_cell = title_row.cells[0] title_cell.value = 'Weekly Timesheet' title_cell.style = title_style sheet.add_merged_region org.apache.poi.ss.util.CellRangeAddress.valueOf("$A$1:$L$1") header_row = sheet[1] header_row.height_in_points = 40 titles.each_with_index do | title, index | header_cell = header_row[index] header_cell.value = title header_cell.style = header_style end row_num = 2 10.times do row = sheet[row_num] row_num += 1 titles.each_with_index do | title, index | cell = row[index] if index == 9 cell.formula = "SUM(C#{row_num}:I#{row_num})" cell.style = form1_style elsif index == 11 cell.formula = "J#{row_num} - K#{row_num}" cell.style = form1_style else cell.style = cell_style end end end # row with totals below sum_row = sheet[row_num] row_num += 1 sum_row.height_in_points = 35 cell = sum_row[0] cell.style = form1_style cell = sum_row[1] cell.style = form1_style cell.value = 'Total Hrs:' (2...12).each do | cell_index | cell = sum_row[cell_index] column = (?A + cell_index).chr cell.formula = "SUM(#{column}3:#{column}12)" if cell_index > 9 cell.style = form2_style else cell.style = form1_style end end row_num += 1 sum_row = sheet[row_num] row_num += 1 sum_row.height_in_points = 25 cell = sum_row[0] cell.value = 'Total Regular Hours' cell.style = form1_style cell = sum_row[1] cell.formula = 'L13' cell.style = form2_style sum_row = sheet[row_num] row_num += 1 cell = sum_row[0] cell.value = 'Total Overtime Hours' cell.style = form1_style cell = sum_row[1] cell.formula = 'K13' cell.style = form2_style # set sample data sample_data.each_with_index do |each, row_index| row = sheet[2 + row_index] each.each_with_index do | data, cell_index | data = sample_data[row_index][cell_index] next unless data if data.kind_of? String row[cell_index].value = data #.to_java(:string) else row[cell_index].value = data #.to_java(:double) end end end # finally set column widths, the width is measured in units of 1/256th of a character width sheet.set_column_width 0, 30*256 # 30 characters wide (2..9).to_a.each do | column | sheet.set_column_width column, 6*256 # 6 characters wide end sheet.set_column_width 10, 10*256 # 10 characters wide book.save File.exist?(name).should == true end end
kameeoze/jruby-poi
3c32d89abe6d87dea69dd1318468db4f30bba93d
Regenerate gemspec for version 0.8.0
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index 7f5b26d..e76e44e 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,86 +1,97 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{jruby-poi} - s.version = "0.7.2" + s.version = "0.8.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Scott Deming", "Jason Rogers"] - s.date = %q{2011-03-31} + s.date = %q{2011-05-22} s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} s.email = ["[email protected]", "[email protected]"] s.executables = ["autospec", "htmldiff", "ldiff", "rdebug", "rspec"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ + ".travis.yml", "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "bin/autospec", "bin/htmldiff", "bin/ldiff", "bin/rdebug", "bin/rspec", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", - "lib/poi-3.6-20091214.jar", - "lib/poi-contrib-3.6-20091214.jar", - "lib/poi-examples-3.6-20091214.jar", - "lib/poi-ooxml-3.6-20091214.jar", - "lib/poi-ooxml-schemas-3.6-20091214.jar", - "lib/poi-scratchpad-3.6-20091214.jar", + "lib/poi-3.7-20101029.jar", + "lib/poi-examples-3.7-20101029.jar", + "lib/poi-ooxml-3.7-20101029.jar", + "lib/poi-ooxml-schemas-3.7-20101029.jar", + "lib/poi-scratchpad-3.7-20101029.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", - "spec_debug.sh", - "specs/data/simple_with_picture.ods", - "specs/data/simple_with_picture.xls", - "specs/data/spreadsheet.ods", - "specs/data/timesheet.xlsx", - "specs/data/various_samples.xlsx", - "specs/facade_spec.rb", - "specs/io_spec.rb", - "specs/spec_helper.rb", - "specs/support/java/jrubypoi/MockOutputStream.java", - "specs/support/java/support.jar", - "specs/support/matchers/cell_matcher.rb", - "specs/workbook_spec.rb", - "specs/writing_spec.rb" + "spec/data/simple_with_picture.ods", + "spec/data/simple_with_picture.xls", + "spec/data/spreadsheet.ods", + "spec/data/timesheet.xlsx", + "spec/data/various_samples.xlsx", + "spec/facade_spec.rb", + "spec/io_spec.rb", + "spec/spec_helper.rb", + "spec/support/java/jrubypoi/MockOutputStream.java", + "spec/support/java/support.jar", + "spec/support/matchers/cell_matcher.rb", + "spec/workbook_spec.rb", + "spec/writing_spec.rb", + "spec_debug.sh" ] - s.homepage = %q{http://github.com/sdeming/jruby-poi} + s.homepage = %q{http://github.com/kameeoze/jruby-poi} s.require_paths = ["lib"] s.rubygems_version = %q{1.5.1} s.summary = %q{Apache POI class library for jruby} + s.test_files = [ + "spec/facade_spec.rb", + "spec/io_spec.rb", + "spec/spec_helper.rb", + "spec/support/matchers/cell_matcher.rb", + "spec/workbook_spec.rb", + "spec/writing_spec.rb" + ] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q<rspec>, [">= 0"]) - s.add_development_dependency(%q<ruby-debug>, [">= 0"]) + s.add_development_dependency(%q<rspec>, [">= 2.5.0"]) + s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) + s.add_development_dependency(%q<rcov>, [">= 0"]) else - s.add_dependency(%q<rspec>, [">= 0"]) - s.add_dependency(%q<ruby-debug>, [">= 0"]) + s.add_dependency(%q<rspec>, [">= 2.5.0"]) + s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) + s.add_dependency(%q<rcov>, [">= 0"]) end else - s.add_dependency(%q<rspec>, [">= 0"]) - s.add_dependency(%q<ruby-debug>, [">= 0"]) + s.add_dependency(%q<rspec>, [">= 2.5.0"]) + s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) + s.add_dependency(%q<rcov>, [">= 0"]) end end
kameeoze/jruby-poi
eafb780cae862c3eb8c24b6b9f6b6abcd6c1a85c
Version bump to 0.8.0
diff --git a/VERSION b/VERSION index d5cc44d..8adc70f 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.7.2 \ No newline at end of file +0.8.0 \ No newline at end of file
kameeoze/jruby-poi
2730f8ae0dd6d7f8d1200c0091d0b1a3b41ea20f
Fixing up specs. Admitting poi doesn't and likely will not support odf :(
diff --git a/Rakefile b/Rakefile index bf3ab8b..adf2782 100644 --- a/Rakefile +++ b/Rakefile @@ -1,36 +1,33 @@ +require 'bundler/setup' +require 'rspec/core/rake_task' + begin require 'jeweler' Jeweler::Tasks.new do |gemspec| gemspec.name = "jruby-poi" gemspec.summary = "Apache POI class library for jruby" gemspec.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." gemspec.email = ["[email protected]", "[email protected]"] - gemspec.homepage = "http://github.com/sdeming/jruby-poi" + gemspec.homepage = "http://github.com/kameeoze/jruby-poi" gemspec.authors = ["Scott Deming", "Jason Rogers"] end rescue LoadError puts "Jeweler not available. Install it with: gem install jeweler" end begin - require 'rspec/core/rake_task' task :default => :spec desc "Run all examples" - RSpec::Core::RakeTask.new do |t| - t.pattern = 'specs/**/*.rb' - t.rspec_opts = ['-c'] - end + RSpec::Core::RakeTask.new(:spec) - desc "Run all examples with RCov" + desc "Run all examples with rcov" RSpec::Core::RakeTask.new(:coverage) do |t| - t.pattern = 'specs/**/*.rb' - t.rspec_opts = ['-c'] t.rcov = true t.rcov_opts = ['--include', '/lib/', '--exclude', '/gems/,/^specs/,/^.eval.$/'] end rescue puts $!.message puts "RCov not available. Install it with: gem install rcov (--no-rdoc --no-ri)" end diff --git a/specs/data/simple_with_picture.ods b/spec/data/simple_with_picture.ods similarity index 100% rename from specs/data/simple_with_picture.ods rename to spec/data/simple_with_picture.ods diff --git a/specs/data/simple_with_picture.xls b/spec/data/simple_with_picture.xls similarity index 100% rename from specs/data/simple_with_picture.xls rename to spec/data/simple_with_picture.xls diff --git a/specs/data/spreadsheet.ods b/spec/data/spreadsheet.ods similarity index 100% rename from specs/data/spreadsheet.ods rename to spec/data/spreadsheet.ods diff --git a/specs/data/timesheet.xlsx b/spec/data/timesheet.xlsx similarity index 100% rename from specs/data/timesheet.xlsx rename to spec/data/timesheet.xlsx diff --git a/specs/data/various_samples.xlsx b/spec/data/various_samples.xlsx similarity index 100% rename from specs/data/various_samples.xlsx rename to spec/data/various_samples.xlsx diff --git a/specs/facade_spec.rb b/spec/facade_spec.rb similarity index 97% rename from specs/facade_spec.rb rename to spec/facade_spec.rb index 4b5e4da..970cd38 100644 --- a/specs/facade_spec.rb +++ b/spec/facade_spec.rb @@ -1,48 +1,46 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') - describe "POI.Facade" do it "should create specialized methods for boolean methods, getters, and setters" do book = POI::Workbook.create('foo.xlsx') sheet = book.create_sheet sheet.respond_to?(:column_broken?).should be_true sheet.respond_to?(:column_hidden?).should be_true sheet.respond_to?(:display_formulas?).should be_true sheet.respond_to?(:display_gridlines?).should be_true sheet.respond_to?(:selected?).should be_true sheet.respond_to?(:column_breaks).should be_true sheet.respond_to?(:column_break=).should be_true sheet.respond_to?(:autobreaks?).should be_true sheet.respond_to?(:autobreaks=).should be_true sheet.respond_to?(:autobreaks!).should be_true sheet.respond_to?(:column_broken?).should be_true sheet.respond_to?(:fit_to_page).should be_true sheet.respond_to?(:fit_to_page?).should be_true sheet.respond_to?(:fit_to_page=).should be_true sheet.respond_to?(:fit_to_page!).should be_true sheet.respond_to?(:array_formula).should_not be_true sheet.respond_to?(:array_formula=).should_not be_true row = sheet[0] row.respond_to?(:first_cell_num).should be_true row.respond_to?(:height).should be_true row.respond_to?(:height=).should be_true row.respond_to?(:height_in_points).should be_true row.respond_to?(:height_in_points=).should be_true row.respond_to?(:zero_height?).should be_true row.respond_to?(:zero_height!).should be_true row.respond_to?(:zero_height=).should be_true cell = row[0] cell.respond_to?(:boolean_cell_value).should be_true cell.respond_to?(:boolean_cell_value?).should be_true cell.respond_to?(:cached_formula_result_type).should be_true cell.respond_to?(:cell_error_value=).should be_true cell.respond_to?(:cell_value=).should be_true cell.respond_to?(:hyperlink=).should be_true cell.respond_to?(:cell_value!).should be_true cell.respond_to?(:remove_cell_comment!).should be_true cell.respond_to?(:cell_style).should be_true cell.respond_to?(:cell_style=).should be_true end -end \ No newline at end of file +end diff --git a/specs/io_spec.rb b/spec/io_spec.rb similarity index 95% rename from specs/io_spec.rb rename to spec/io_spec.rb index d1d247a..c022c3b 100644 --- a/specs/io_spec.rb +++ b/spec/io_spec.rb @@ -1,69 +1,67 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') - describe POI::Workbook do before :each do @mock_output_stream = nil class POI::Workbook def mock_output_stream name @mock_output_stream ||= Java::jrubypoi.MockOutputStream.new name @mock_output_stream end alias_method :original_output_stream, :output_stream unless method_defined?(:original_output_stream) alias_method :output_stream, :mock_output_stream end end after :each do @mock_output_stream = nil class POI::Workbook alias_method :output_stream, :original_output_stream end end it "should read an xlsx file" do name = TestDataFile.expand_path("various_samples.xlsx") book = nil lambda { book = POI::Workbook.open(name) }.should_not raise_exception book.should be_kind_of POI::Workbook end it "should read an xls file" do name = TestDataFile.expand_path("simple_with_picture.xls") book = nil lambda { book = POI::Workbook.open(name) }.should_not raise_exception book.should be_kind_of POI::Workbook end - it "should read an ods file" do + it "should read an ods file", :unimplemented => true do name = TestDataFile.expand_path("spreadsheet.ods") book = nil lambda { book = POI::Workbook.open(name) }.should_not raise_exception book.should be_kind_of POI::Workbook end it "should write an open workbook" do name = TestDataFile.expand_path("various_samples.xlsx") POI::Workbook.open(name) do |book| lambda { book.save }.should_not raise_exception verify_mock_output_stream book.instance_variable_get("@mock_output_stream"), name end end it "should write an open workbook to a new file" do name = TestDataFile.expand_path("various_samples.xlsx") new_name = TestDataFile.expand_path("saved-as.xlsx") POI::Workbook.open(name) do |book| @mock_output_stream.should be_nil lambda { book.save_as(new_name) }.should_not raise_exception verify_mock_output_stream book.instance_variable_get("@mock_output_stream"), new_name end end def verify_mock_output_stream mock_output_stream, name mock_output_stream.should_not be_nil name.should == mock_output_stream.name true.should == mock_output_stream.write_called end end diff --git a/specs/spec_helper.rb b/spec/spec_helper.rb similarity index 60% rename from specs/spec_helper.rb rename to spec/spec_helper.rb index 93933cf..5e19c22 100644 --- a/specs/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,10 +1,15 @@ -require 'rspec' -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'poi')) +$stderr.puts "included spec_helper.rb" +RSpec.configure do |c| + c.filter_run_excluding :unimplemented => true +end + +require File.expand_path('../lib/poi', File.dirname(__FILE__)) + Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f} require File.join(File.dirname(__FILE__), "support", "java", "support.jar") class TestDataFile def self.expand_path(name) File.expand_path(File.join(File.dirname(__FILE__), 'data', name)) end end diff --git a/specs/support/java/jrubypoi/MockOutputStream.java b/spec/support/java/jrubypoi/MockOutputStream.java similarity index 100% rename from specs/support/java/jrubypoi/MockOutputStream.java rename to spec/support/java/jrubypoi/MockOutputStream.java diff --git a/specs/support/java/support.jar b/spec/support/java/support.jar similarity index 100% rename from specs/support/java/support.jar rename to spec/support/java/support.jar diff --git a/specs/support/matchers/cell_matcher.rb b/spec/support/matchers/cell_matcher.rb similarity index 100% rename from specs/support/matchers/cell_matcher.rb rename to spec/support/matchers/cell_matcher.rb diff --git a/specs/workbook_spec.rb b/spec/workbook_spec.rb similarity index 99% rename from specs/workbook_spec.rb rename to spec/workbook_spec.rb index df67355..166f314 100644 --- a/specs/workbook_spec.rb +++ b/spec/workbook_spec.rb @@ -1,369 +1,369 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') +require 'spec_helper' require 'date' require 'stringio' describe POI::Workbook do it "should open a workbook and allow access to its worksheets" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets.size.should == 5 book.filename.should == name end it "should be able to create a Workbook from an IO object" do content = StringIO.new(open(TestDataFile.expand_path("various_samples.xlsx"), 'rb'){|f| f.read}) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should be able to create a Workbook from a Java input stream" do content = java.io.FileInputStream.new(TestDataFile.expand_path("various_samples.xlsx")) book = POI::Workbook.open(content) book.worksheets.size.should == 5 book.filename.should =~ /spreadsheet.xlsx$/ end it "should return a column of cells by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} end it "should return cells by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.cell("numbers!A1").value.should == 'NUM' book.cell("numbers!A2").to_s.should == '1.0' book.cell("numbers!A3").to_s.should == '2.0' book.cell("numbers!A4").to_s.should == '3.0' book.cell("numbers!A10").to_s.should == '9.0' book.cell("numbers!B10").to_s.should == '81.0' book.cell("numbers!C10").to_s.should == '729.0' book.cell("numbers!D10").to_s.should == '3.0' book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' book.cell("bools & errors!B3").value.should == true book.cell("high refs!AM619").value.should == 'This is some text' book.cell("high refs!AO624").value.should == 24.0 book.cell("high refs!AP631").value.should == 13.0 book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' book.cell(%Q{'bools & errors'!B3}).value.should == true book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' book.cell(%Q{'high refs'!AO624}).value.should == 24.0 book.cell(%Q{'high refs'!AP631}).value.should == 13.0 end it "should handle named cell ranges" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.named_ranges.length.should == 3 book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] book['four_times_six'].should == 24.0 book['nums'].should == (1..13).collect{|e| e * 1.0} # NAMES is a range of empty cells book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] book.cell('NAMES').each do | cell | cell.value.should be_nil cell.poi_cell.should_not be_nil cell.to_s.should be_empty end end it "should return an array of cell values by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book['dates!A2:A16'].should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a end it "should return cell values by reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' book['bools & errors!B3'].should == true book['high refs!AM619'].should == 'This is some text' book['high refs!AO624'].should == 24.0 book['high refs!AP631'].should == 13.0 end end describe POI::Worksheets do it "should allow indexing worksheets by ordinal" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets[0].name.should == "text & pic" book.worksheets[1].name.should == "numbers" book.worksheets[2].name.should == "dates" book.worksheets[3].name.should == "bools & errors" end it "should allow indexing worksheets by name" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets["text & pic"].name.should == "text & pic" book.worksheets["numbers"].name.should == "numbers" book.worksheets["dates"].name.should == "dates" end it "should be enumerable" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book.worksheets.should be_kind_of Enumerable book.worksheets.each do |sheet| sheet.should be_kind_of POI::Worksheet end book.worksheets.size.should == 5 book.worksheets.collect.size.should == 5 end it "returns cells when passing a cell reference" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) book['dates']['A2'].to_s.should == '2010-02-28' book['dates']['a2'].to_s.should == '2010-02-28' book['dates']['B2'].to_s.should == '2010-03-14' book['dates']['b2'].to_s.should == '2010-03-14' book['dates']['C2'].to_s.should == '2010-03-28' book['dates']['c2'].to_s.should == '2010-03-28' end end describe POI::Rows do it "should be enumerable" do name = TestDataFile.expand_path("various_samples.xlsx") book = POI::Workbook.open(name) sheet = book.worksheets["text & pic"] sheet.rows.should be_kind_of Enumerable sheet.rows.each do |row| row.should be_kind_of POI::Row end sheet.rows.size.should == 7 sheet.rows.collect.size.should == 7 end end describe POI::Cells do before :each do @name = TestDataFile.expand_path("various_samples.xlsx") @book = POI::Workbook.open(@name) end def book @book end def name @name end it "should be enumerable" do sheet = book.worksheets["text & pic"] rows = sheet.rows cells = rows[0].cells cells.should be_kind_of Enumerable cells.size.should == 1 cells.collect.size.should == 1 end end describe POI::Cell do before :each do @name = TestDataFile.expand_path("various_samples.xlsx") @book = POI::Workbook.open(@name) end def book @book end def name @name end it "should provide dates for date cells" do sheet = book.worksheets["dates"] rows = sheet.rows dates_by_column = [ (Date.parse('2010-02-28')..Date.parse('2010-03-14')), (Date.parse('2010-03-14')..Date.parse('2010-03-28')), (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] (0..2).each do |col| dates_by_column[col].each_with_index do |date, index| row = index + 1 rows[row][col].value.should equal_at_cell(date, row, col) end end end it "should provide numbers for numeric cells" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].value.should equal_at_cell(number, row, 0) rows[row][1].value.should equal_at_cell(number ** 2, row, 1) rows[row][2].value.should equal_at_cell(number ** 3, row, 2) rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) end rows[9][0].to_s.should == '9.0' rows[9][1].to_s.should == '81.0' rows[9][2].to_s.should == '729.0' rows[9][3].to_s.should == '3.0' end it "should handle array access from the workbook down to cells" do book[1][9][0].to_s.should == '9.0' book[1][9][1].to_s.should == '81.0' book[1][9][2].to_s.should == '729.0' book[1][9][3].to_s.should == '3.0' book["numbers"][9][0].to_s.should == '9.0' book["numbers"][9][1].to_s.should == '81.0' book["numbers"][9][2].to_s.should == '729.0' book["numbers"][9][3].to_s.should == '3.0' end it "should provide error text for error cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' rows[6][0].error_value.should be_nil rows[7][0].value.should be_nil rows[7][0].error_value.should == '#DIV/0!' rows[8][0].value.should be_nil rows[8][0].error_value.should == '#N/A' rows[9][0].value.should be_nil rows[9][0].error_value.should == '#NAME?' rows[10][0].value.should be_nil rows[10][0].error_value.should == '#NULL!' rows[11][0].value.should be_nil rows[11][0].error_value.should == '#NUM!' rows[12][0].value.should be_nil rows[12][0].error_value.should == '#REF!' rows[13][0].value.should be_nil rows[13][0].error_value.should == '#VALUE!' lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' rows[7][0].to_s.should == '' #'#DIV/0!' rows[8][0].to_s.should == '' #'#N/A' rows[9][0].to_s.should == '' #'#NAME?' rows[10][0].to_s.should == '' #'#NULL!' rows[11][0].to_s.should == '' #'#NUM!' rows[12][0].to_s.should == '' #'#REF!' rows[13][0].to_s.should == '' #'#VALUE!' rows[14][0].to_s.should == '' end it "should provide booleans for boolean cells" do sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].value.should == false rows[1][0].to_s.should == 'false' rows[1][1].value.should == false rows[1][1].to_s.should == 'false' rows[2][0].value.should == true rows[2][0].to_s.should == 'true' rows[2][1].value.should == true rows[2][1].to_s.should == 'true' end it "should provide the cell value as a string" do sheet = book.worksheets["text & pic"] rows = sheet.rows rows[0][0].value.should == "This" rows[1][0].value.should == "is" rows[2][0].value.should == "an" rows[3][0].value.should == "Excel" rows[4][0].value.should == "XLSX" rows[5][0].value.should == "workbook" rows[9][0].value.should == 'This is an Excel XLSX workbook.' rows[0][0].to_s.should == "This" rows[1][0].to_s.should == "is" rows[2][0].to_s.should == "an" rows[3][0].to_s.should == "Excel" rows[4][0].to_s.should == "XLSX" rows[5][0].to_s.should == "workbook" rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' end it "should provide formulas instead of string-ified values" do sheet = book.worksheets["numbers"] rows = sheet.rows (1..15).each do |number| row = number rows[row][0].to_s(false).should == "#{number}.0" rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" end sheet = book.worksheets["bools & errors"] rows = sheet.rows rows[1][0].to_s(false).should == '1=2' rows[1][1].to_s(false).should == 'FALSE' rows[2][0].to_s(false).should == '1=1' rows[2][1].to_s(false).should == 'TRUE' rows[14][0].to_s(false).should == 'foobar(1)' sheet = book.worksheets["text & pic"] sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' end it "should handle getting values out of 'non-existent' cells" do sheet = book.worksheets["bools & errors"] sheet.rows[14][2].value.should be_nil end it "should notify the workbook that I have been updated" do book['dates!A10'].to_s.should == '2010-03-08' book['dates!A16'].to_s.should == '2010-03-14' book['dates!B2'].to_s.should == '2010-03-14' cell = book.cell('dates!B2') cell.formula.should == 'A16' cell.formula = 'A10 + 1' book.cell('dates!B2').poi_cell.should === cell.poi_cell book.cell('dates!B2').formula.should == 'A10 + 1' book['dates!B2'].to_s.should == '2010-03-09' end end diff --git a/specs/writing_spec.rb b/spec/writing_spec.rb similarity index 96% rename from specs/writing_spec.rb rename to spec/writing_spec.rb index 472a2ba..281b0af 100644 --- a/specs/writing_spec.rb +++ b/spec/writing_spec.rb @@ -1,145 +1,144 @@ -require File.join(File.dirname(__FILE__), 'spec_helper') require 'date' require 'stringio' describe "writing Workbooks" do it "should create a new empty workbook" do name = 'new-workbook.xlsx' book = POI::Workbook.create(name) book.should_not be_nil end it "should create a new workbook and write something to it" do - name = "specs/data/timesheet-#{Time.now.strftime('%Y%m%d%H%M%S%s')}.xlsx" + name = "spec/data/timesheet-#{Time.now.strftime('%Y%m%d%H%M%S%s')}.xlsx" create_timesheet_spreadsheet(name) book = POI::Workbook.open(name) book.worksheets.size.should == 1 book.worksheets[0].name.should == 'Timesheet' book.filename.should == name book['Timesheet!A3'].should == 'Yegor Kozlov' book.cell('Timesheet!J13').formula_value.should == 'SUM(J3:J12)' FileUtils.rm_f name end - def create_timesheet_spreadsheet name='specs/data/timesheet.xlsx' + def create_timesheet_spreadsheet name='spec/data/timesheet.xlsx' titles = ["Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Total\nHrs", "Overtime\nHrs", "Regular\nHrs"] sample_data = [ ["Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0], ["Gisella Bronzetti", "GB", 4.0, 3.0, 1.0, 3.5, nil, nil, 4.0] ] book = POI::Workbook.create(name) title_style = book.create_style :font_height_in_points => 18, :boldweight => :boldweight_bold, :alignment => :align_center, :vertical_alignment => :vertical_center header_style = book.create_style :font_height_in_points => 11, :color => :white, :fill_foreground_color => :grey_50_percent, :fill_pattern => :solid_foreground, :alignment => :align_center, :vertical_alignment => :vertical_center cell_style = book.create_style :alignment => :align_center, :border_bottom => :border_thin, :border_top => :border_thin, :border_left => :border_thin, :border_right => :border_thin, :bottom_border_color => :black, :right_border_color => :black, :left_border_color => :black, :top_border_color => :black form1_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_25_percent, :alignment => :align_center, :vertical_alignment => :vertical_center form2_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_40_percent, :alignment => :align_center, :vertical_alignment => :vertical_center sheet = book.create_sheet 'Timesheet' print_setup = sheet.print_setup print_setup.landscape = true sheet.fit_to_page = true sheet.horizontally_center = true title_row = sheet.rows[0] title_row.height_in_points = 45 title_cell = title_row.cells[0] title_cell.value = 'Weekly Timesheet' title_cell.style = title_style sheet.add_merged_region org.apache.poi.ss.util.CellRangeAddress.valueOf("$A$1:$L$1") header_row = sheet[1] header_row.height_in_points = 40 titles.each_with_index do | title, index | header_cell = header_row[index] header_cell.value = title header_cell.style = header_style end row_num = 2 10.times do row = sheet[row_num] row_num += 1 titles.each_with_index do | title, index | cell = row[index] if index == 9 cell.formula = "SUM(C#{row_num}:I#{row_num})" cell.style = form1_style elsif index == 11 cell.formula = "J#{row_num} - K#{row_num}" cell.style = form1_style else cell.style = cell_style end end end # row with totals below sum_row = sheet[row_num] row_num += 1 sum_row.height_in_points = 35 cell = sum_row[0] cell.style = form1_style cell = sum_row[1] cell.style = form1_style cell.value = 'Total Hrs:' (2...12).each do | cell_index | cell = sum_row[cell_index] column = (?A + cell_index).chr cell.formula = "SUM(#{column}3:#{column}12)" if cell_index > 9 cell.style = form2_style else cell.style = form1_style end end row_num += 1 sum_row = sheet[row_num] row_num += 1 sum_row.height_in_points = 25 cell = sum_row[0] cell.value = 'Total Regular Hours' cell.style = form1_style cell = sum_row[1] cell.formula = 'L13' cell.style = form2_style sum_row = sheet[row_num] row_num += 1 cell = sum_row[0] cell.value = 'Total Overtime Hours' cell.style = form1_style cell = sum_row[1] cell.formula = 'K13' cell.style = form2_style # set sample data sample_data.each_with_index do |each, row_index| row = sheet[2 + row_index] each.each_with_index do | data, cell_index | data = sample_data[row_index][cell_index] next unless data if data.kind_of? String row[cell_index].value = data #.to_java(:string) else row[cell_index].value = data #.to_java(:double) end end end # finally set column widths, the width is measured in units of 1/256th of a character width sheet.set_column_width 0, 30*256 # 30 characters wide (2..9).to_a.each do | column | sheet.set_column_width column, 6*256 # 6 characters wide end sheet.set_column_width 10, 10*256 # 10 characters wide book.save File.exist?(name).should == true end -end \ No newline at end of file +end
kameeoze/jruby-poi
1032ff6b6637fb62818c41a37dc42f140f76ae73
Fixed deprecated task
diff --git a/specs/spec_helper.rb b/specs/spec_helper.rb index 9fdc232..93933cf 100644 --- a/specs/spec_helper.rb +++ b/specs/spec_helper.rb @@ -1,13 +1,10 @@ require 'rspec' require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'poi')) Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f} require File.join(File.dirname(__FILE__), "support", "java", "support.jar") class TestDataFile def self.expand_path(name) File.expand_path(File.join(File.dirname(__FILE__), 'data', name)) end end - -RSpec.configure do |config| -end
kameeoze/jruby-poi
5792fcce9feddd66d7e1f3a5fb4fd93f5efeae09
added geronimo stax parser.
diff --git a/lib/poi.rb b/lib/poi.rb index 3be2d80..43d64f0 100644 --- a/lib/poi.rb +++ b/lib/poi.rb @@ -1,13 +1,15 @@ JRUBY_POI_LIB_PATH=File.expand_path(File.dirname(__FILE__)) # Java require 'java' require File.join(JRUBY_POI_LIB_PATH, 'poi-3.7-20101029.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-3.7-20101029.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-schemas-3.7-20101029.jar') require File.join(JRUBY_POI_LIB_PATH, 'poi-scratchpad-3.7-20101029.jar') require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'xmlbeans-2.3.0.jar') require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'dom4j-1.6.1.jar') +require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'geronimo-stax-api_1.0_spec-1.0.jar') + # Ruby require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook')
kameeoze/jruby-poi
dbd7c1d358662e164fc66e0e85a075ce1f35ccee
Adding guidance to travis-ci
diff --git a/.travis-ci.yml b/.travis-ci.yml new file mode 100644 index 0000000..da1b1ae --- /dev/null +++ b/.travis-ci.yml @@ -0,0 +1,2 @@ +rvm: + - jruby
kameeoze/jruby-poi
7681e7fbeadcaea646a00a75a2689ecd3eadd6ee
Upgrading to poi 3.7.
diff --git a/Gemfile b/Gemfile index b838c20..9540af9 100644 --- a/Gemfile +++ b/Gemfile @@ -1,6 +1,9 @@ -source 'http://rubygems.org' +source "http://rubygems.org" +# Add dependencies to develop your gem here. +# Include everything needed to run rake, tests, features, etc. group :development do - gem 'rspec' - gem 'ruby-debug' + gem "rspec", ">= 2.5.0" + gem "jeweler", "~> 1.5.2" + gem "rcov", ">= 0" end diff --git a/Gemfile.lock b/Gemfile.lock index 8763d6a..32ceb9b 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,25 +1,29 @@ GEM remote: http://rubygems.org/ specs: - columnize (0.3.2) diff-lcs (1.1.2) - rspec (2.5.0) - rspec-core (~> 2.5.0) - rspec-expectations (~> 2.5.0) - rspec-mocks (~> 2.5.0) - rspec-core (2.5.1) - rspec-expectations (2.5.0) + git (1.2.5) + jeweler (1.5.2) + bundler (~> 1.0.0) + git (>= 1.2.5) + rake + rake (0.9.0) + rcov (0.9.9) + rcov (0.9.9-java) + rspec (2.6.0) + rspec-core (~> 2.6.0) + rspec-expectations (~> 2.6.0) + rspec-mocks (~> 2.6.0) + rspec-core (2.6.2) + rspec-expectations (2.6.0) diff-lcs (~> 1.1.2) - rspec-mocks (2.5.0) - ruby-debug (0.10.4) - columnize (>= 0.1) - ruby-debug-base (~> 0.10.4.0) - ruby-debug-base (0.10.4-java) + rspec-mocks (2.6.0) PLATFORMS java ruby DEPENDENCIES - rspec - ruby-debug + jeweler (~> 1.5.2) + rcov + rspec (>= 2.5.0) diff --git a/lib/poi-3.6-20091214.jar b/lib/poi-3.7-20101029.jar similarity index 56% rename from lib/poi-3.6-20091214.jar rename to lib/poi-3.7-20101029.jar index 9972d97..a08d953 100644 Binary files a/lib/poi-3.6-20091214.jar and b/lib/poi-3.7-20101029.jar differ diff --git a/lib/poi-contrib-3.6-20091214.jar b/lib/poi-contrib-3.6-20091214.jar deleted file mode 100644 index 07403a9..0000000 Binary files a/lib/poi-contrib-3.6-20091214.jar and /dev/null differ diff --git a/lib/poi-examples-3.6-20091214.jar b/lib/poi-examples-3.7-20101029.jar similarity index 53% rename from lib/poi-examples-3.6-20091214.jar rename to lib/poi-examples-3.7-20101029.jar index 988e39e..914243d 100644 Binary files a/lib/poi-examples-3.6-20091214.jar and b/lib/poi-examples-3.7-20101029.jar differ diff --git a/lib/poi-ooxml-3.6-20091214.jar b/lib/poi-ooxml-3.6-20091214.jar deleted file mode 100644 index c986646..0000000 Binary files a/lib/poi-ooxml-3.6-20091214.jar and /dev/null differ diff --git a/lib/poi-ooxml-3.7-20101029.jar b/lib/poi-ooxml-3.7-20101029.jar new file mode 100644 index 0000000..5f36eb4 Binary files /dev/null and b/lib/poi-ooxml-3.7-20101029.jar differ diff --git a/lib/poi-ooxml-schemas-3.6-20091214.jar b/lib/poi-ooxml-schemas-3.7-20101029.jar similarity index 56% rename from lib/poi-ooxml-schemas-3.6-20091214.jar rename to lib/poi-ooxml-schemas-3.7-20101029.jar index 5b79f02..82282b5 100644 Binary files a/lib/poi-ooxml-schemas-3.6-20091214.jar and b/lib/poi-ooxml-schemas-3.7-20101029.jar differ diff --git a/lib/poi-scratchpad-3.6-20091214.jar b/lib/poi-scratchpad-3.7-20101029.jar similarity index 70% rename from lib/poi-scratchpad-3.6-20091214.jar rename to lib/poi-scratchpad-3.7-20101029.jar index 1a01b2b..6fd02d4 100644 Binary files a/lib/poi-scratchpad-3.6-20091214.jar and b/lib/poi-scratchpad-3.7-20101029.jar differ diff --git a/lib/poi.rb b/lib/poi.rb index 12c7bdc..3be2d80 100644 --- a/lib/poi.rb +++ b/lib/poi.rb @@ -1,14 +1,13 @@ JRUBY_POI_LIB_PATH=File.expand_path(File.dirname(__FILE__)) # Java require 'java' -require File.join(JRUBY_POI_LIB_PATH, 'poi-3.6-20091214.jar') -require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-3.6-20091214.jar') -require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-schemas-3.6-20091214.jar') -require File.join(JRUBY_POI_LIB_PATH, 'poi-scratchpad-3.6-20091214.jar') -require File.join(JRUBY_POI_LIB_PATH, 'poi-contrib-3.6-20091214.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-3.7-20101029.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-3.7-20101029.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-schemas-3.7-20101029.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-scratchpad-3.7-20101029.jar') require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'xmlbeans-2.3.0.jar') require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'dom4j-1.6.1.jar') # Ruby require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook')
kameeoze/jruby-poi
2dc760f2a70550cb71b1283df738b4b399fef6cc
Regenerate gemspec for version 0.7.2
diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec index 5182d5b..7f5b26d 100644 --- a/jruby-poi.gemspec +++ b/jruby-poi.gemspec @@ -1,86 +1,86 @@ # Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{jruby-poi} - s.version = "0.7.1" + s.version = "0.7.2" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Scott Deming", "Jason Rogers"] s.date = %q{2011-03-31} s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} s.email = ["[email protected]", "[email protected]"] s.executables = ["autospec", "htmldiff", "ldiff", "rdebug", "rspec"] s.extra_rdoc_files = [ "LICENSE", "README.markdown" ] s.files = [ "Gemfile", "Gemfile.lock", "LICENSE", "NOTICE", "README.markdown", "Rakefile", "VERSION", "bin/autospec", "bin/htmldiff", "bin/ldiff", "bin/rdebug", "bin/rspec", "jruby-poi.gemspec", "lib/ooxml-lib/dom4j-1.6.1.jar", "lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar", "lib/ooxml-lib/xmlbeans-2.3.0.jar", "lib/poi-3.6-20091214.jar", "lib/poi-contrib-3.6-20091214.jar", "lib/poi-examples-3.6-20091214.jar", "lib/poi-ooxml-3.6-20091214.jar", "lib/poi-ooxml-schemas-3.6-20091214.jar", "lib/poi-scratchpad-3.6-20091214.jar", "lib/poi.rb", "lib/poi/workbook.rb", "lib/poi/workbook/area.rb", "lib/poi/workbook/cell.rb", "lib/poi/workbook/named_range.rb", "lib/poi/workbook/row.rb", "lib/poi/workbook/workbook.rb", "lib/poi/workbook/worksheet.rb", "spec_debug.sh", "specs/data/simple_with_picture.ods", "specs/data/simple_with_picture.xls", "specs/data/spreadsheet.ods", "specs/data/timesheet.xlsx", "specs/data/various_samples.xlsx", "specs/facade_spec.rb", "specs/io_spec.rb", "specs/spec_helper.rb", "specs/support/java/jrubypoi/MockOutputStream.java", "specs/support/java/support.jar", "specs/support/matchers/cell_matcher.rb", "specs/workbook_spec.rb", "specs/writing_spec.rb" ] s.homepage = %q{http://github.com/sdeming/jruby-poi} s.require_paths = ["lib"] s.rubygems_version = %q{1.5.1} s.summary = %q{Apache POI class library for jruby} if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<rspec>, [">= 0"]) s.add_development_dependency(%q<ruby-debug>, [">= 0"]) else s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<ruby-debug>, [">= 0"]) end else s.add_dependency(%q<rspec>, [">= 0"]) s.add_dependency(%q<ruby-debug>, [">= 0"]) end end
kameeoze/jruby-poi
198e05876fafc3cce5ce365369388c09e3e2db2d
Version bump to 0.7.2
diff --git a/VERSION b/VERSION index 7deb86f..d5cc44d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.7.1 \ No newline at end of file +0.7.2 \ No newline at end of file
kameeoze/jruby-poi
a26371a115da0be59ede8ca10f4738a0b9fb3230
Regenerate gemspec for version 0.7.1
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4090811 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +.DS_Store +.project +.idea +nbproject +.*~ +tmp +*.swp +TAGS +tags +pkg +.yardoc +documentation +coverage +.bundle diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..b838c20 --- /dev/null +++ b/Gemfile @@ -0,0 +1,6 @@ +source 'http://rubygems.org' + +group :development do + gem 'rspec' + gem 'ruby-debug' +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..8763d6a --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,25 @@ +GEM + remote: http://rubygems.org/ + specs: + columnize (0.3.2) + diff-lcs (1.1.2) + rspec (2.5.0) + rspec-core (~> 2.5.0) + rspec-expectations (~> 2.5.0) + rspec-mocks (~> 2.5.0) + rspec-core (2.5.1) + rspec-expectations (2.5.0) + diff-lcs (~> 1.1.2) + rspec-mocks (2.5.0) + ruby-debug (0.10.4) + columnize (>= 0.1) + ruby-debug-base (~> 0.10.4.0) + ruby-debug-base (0.10.4-java) + +PLATFORMS + java + ruby + +DEPENDENCIES + rspec + ruby-debug diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3f40d40 --- /dev/null +++ b/LICENSE @@ -0,0 +1,507 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + +APACHE POI SUBCOMPONENTS: + +Apache POI includes subcomponents with separate copyright notices and +license terms. Your use of these subcomponents is subject to the terms +and conditions of the following licenses: + + +Office Open XML schemas (ooxml-schemas-1.0.jar) + + The Office Open XML schema definitions used by Apache POI are + a part of the Office Open XML ECMA Specification (ECMA-376, [1]). + As defined in section 9.4 of the ECMA bylaws [2], this specification + is available to all interested parties without restriction: + + 9.4 All documents when approved shall be made available to + all interested parties without restriction. + + Furthermore, both Microsoft and Adobe have granted patent licenses + to this work [3,4,5]. + + [1] http://www.ecma-international.org/publications/standards/Ecma-376.htm + [2] http://www.ecma-international.org/memento/Ecmabylaws.htm + [3] http://www.microsoft.com/interop/osp/ + [4] http://www.ecma-international.org/publications/files/ECMA-ST/Ecma%20PATENT/ECMA-376%20Edition%201%20Microsoft%20Patent%20Declaration.pdf + [5] http://www.ecma-international.org/publications/files/ECMA-ST/Ecma%20PATENT/ga-2006-191.pdf + + +DOM4J library (dom4j-1.6.1.jar) + + Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. + + Redistribution and use of this software and associated documentation + ("Software"), with or without modification, are permitted provided + that the following conditions are met: + + 1. Redistributions of source code must retain copyright + statements and notices. Redistributions must also contain a + copy of this document. + + 2. 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. + + 3. The name "DOM4J" must not be used to endorse or promote + products derived from this Software without prior written + permission of MetaStuff, Ltd. For written permission, + please contact [email protected]. + + 4. Products derived from this Software may not be called "DOM4J" + nor may "DOM4J" appear in their names without prior written + permission of MetaStuff, Ltd. DOM4J is a registered + trademark of MetaStuff, Ltd. + + 5. Due credit should be given to the DOM4J Project - + http://www.dom4j.org + + THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESSED 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 + METASTUFF, LTD. OR ITS 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. + + +JUnit test library (junit-3.8.1.jar) + + Common Public License - v 1.0 + + THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS COMMON + PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION + OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + + 1. DEFINITIONS + + "Contribution" means: + + a) in the case of the initial Contributor, the initial code and + documentation distributed under this Agreement, and + + b) in the case of each subsequent Contributor: + + i) changes to the Program, and + + ii) additions to the Program; + + where such changes and/or additions to the Program originate from + and are distributed by that particular Contributor. A Contribution + 'originates' from a Contributor if it was added to the Program by + such Contributor itself or anyone acting on such Contributor's behalf. + Contributions do not include additions to the Program which: (i) are + separate modules of software distributed in conjunction with the + Program under their own license agreement, and (ii) are not derivative + works of the Program. + + "Contributor" means any person or entity that distributes the Program. + + "Licensed Patents " mean patent claims licensable by a Contributor which + are necessarily infringed by the use or sale of its Contribution alone + or when combined with the Program. + + "Program" means the Contributions distributed in accordance with this + Agreement. + + "Recipient" means anyone who receives the Program under this Agreement, + including all Contributors. + + 2. GRANT OF RIGHTS + + a) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free copyright license + to reproduce, prepare derivative works of, publicly display, publicly + perform, distribute and sublicense the Contribution of such + Contributor, if any, and such derivative works, in source code and + object code form. + + b) Subject to the terms of this Agreement, each Contributor hereby grants + Recipient a non-exclusive, worldwide, royalty-free patent license under + Licensed Patents to make, use, sell, offer to sell, import and + otherwise transfer the Contribution of such Contributor, if any, in + source code and object code form. This patent license shall apply to + the combination of the Contribution and the Program if, at the time + the Contribution is added by the Contributor, such addition of the + Contribution causes such combination to be covered by the Licensed + Patents. The patent license shall not apply to any other combinations + which include the Contribution. No hardware per se is licensed + hereunder. + + c) Recipient understands that although each Contributor grants the + licenses to its Contributions set forth herein, no assurances are + provided by any Contributor that the Program does not infringe the + patent or other intellectual property rights of any other entity. + Each Contributor disclaims any liability to Recipient for claims + brought by any other entity based on infringement of intellectual + property rights or otherwise. As a condition to exercising the rights + and licenses granted hereunder, each Recipient hereby assumes sole + responsibility to secure any other intellectual property rights + needed, if any. For example, if a third party patent license is + required to allow Recipient to distribute the Program, it is + Recipient's responsibility to acquire that license before + distributing the Program. + + d) Each Contributor represents that to its knowledge it has sufficient + copyright rights in its Contribution, if any, to grant the copyright + license set forth in this Agreement. + + 3. REQUIREMENTS + + A Contributor may choose to distribute the Program in object code form + under its own license agreement, provided that: + + a) it complies with the terms and conditions of this Agreement; and + + b) its license agreement: + + i) effectively disclaims on behalf of all Contributors all warranties + and conditions, express and implied, including warranties or + conditions of title and non-infringement, and implied warranties + or conditions of merchantability and fitness for a particular + purpose; + + ii) effectively excludes on behalf of all Contributors all liability + for damages, including direct, indirect, special, incidental and + consequential damages, such as lost profits; + + iii) states that any provisions which differ from this Agreement are + offered by that Contributor alone and not by any other party; and + + iv) states that source code for the Program is available from such + Contributor, and informs licensees how to obtain it in a + reasonable manner on or through a medium customarily used for + software exchange. + + When the Program is made available in source code form: + + a) it must be made available under this Agreement; and + + b) a copy of this Agreement must be included with each copy of + the Program. + + Contributors may not remove or alter any copyright notices contained + within the Program. + + Each Contributor must identify itself as the originator of its + Contribution, if any, in a manner that reasonably allows subsequent + Recipients to identify the originator of the Contribution. + + 4. COMMERCIAL DISTRIBUTION + + Commercial distributors of software may accept certain responsibilities + with respect to end users, business partners and the like. While this + license is intended to facilitate the commercial use of the Program, + the Contributor who includes the Program in a commercial product offering + should do so in a manner which does not create potential liability for + other Contributors. Therefore, if a Contributor includes the Program + in a commercial product offering, such Contributor ("Commercial + Contributor") hereby agrees to defend and indemnify every other + Contributor ("Indemnified Contributor") against any losses, damages + and costs (collectively "Losses") arising from claims, lawsuits and + other legal actions brought by a third party against the Indemnified + Contributor to the extent caused by the acts or omissions of such + Commercial Contributor in connection with its distribution of the + Program in a commercial product offering. The obligations in this + section do not apply to any claims or Losses relating to any actual + or alleged intellectual property infringement. In order to qualify, + an Indemnified Contributor must: a) promptly notify the Commercial + Contributor in writing of such claim, and b) allow the Commercial + Contributor to control, and cooperate with the Commercial Contributor + in, the defense and any related settlement negotiations. The Indemnified + Contributor may participate in any such claim at its own expense. + + For example, a Contributor might include the Program in a commercial + product offering, Product X. That Contributor is then a Commercial + Contributor. If that Commercial Contributor then makes performance + claims, or offers warranties related to Product X, those performance + claims and warranties are such Commercial Contributor's responsibility + alone. Under this section, the Commercial Contributor would have to + defend claims against the other Contributors related to those + performance claims and warranties, and if a court requires any other + Contributor to pay any damages as a result, the Commercial Contributor + must pay those damages. + + 5. NO WARRANTY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED + ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER + EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR + CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR + A PARTICULAR PURPOSE. Each Recipient is solely responsible for + determining the appropriateness of using and distributing the Program + and assumes all risks associated with its exercise of rights under this + Agreement, including but not limited to the risks and costs of program + errors, compliance with applicable laws, damage to or loss of data, + programs or equipment, and unavailability or interruption of operations. + + 6. DISCLAIMER OF LIABILITY + + EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR + ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, + INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING + WITHOUT LIMITATION LOST PROFITS), 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 OR + DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED + HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + 7. GENERAL + + If any provision of this Agreement is invalid or unenforceable under + applicable law, it shall not affect the validity or enforceability of + the remainder of the terms of this Agreement, and without further + action by the parties hereto, such provision shall be reformed to the + minimum extent necessary to make such provision valid and enforceable. + + If Recipient institutes patent litigation against a Contributor with + respect to a patent applicable to software (including a cross-claim or + counterclaim in a lawsuit), then any patent licenses granted by that + Contributor to such Recipient under this Agreement shall terminate as of + the date such litigation is filed. In addition, if Recipient institutes + patent litigation against any entity (including a cross-claim or + counterclaim in a lawsuit) alleging that the Program itself (excluding + combinations of the Program with other software or hardware) infringes + such Recipient's patent(s), then such Recipient's rights granted under + Section 2(b) shall terminate as of the date such litigation is filed. + + All Recipient's rights under this Agreement shall terminate if it fails + to comply with any of the material terms or conditions of this Agreement + and does not cure such failure in a reasonable period of time after + becoming aware of such noncompliance. If all Recipient's rights under + this Agreement terminate, Recipient agrees to cease use and distribution + of the Program as soon as reasonably practicable. However, Recipient's + obligations under this Agreement and any licenses granted by Recipient + relating to the Program shall continue and survive. + + Everyone is permitted to copy and distribute copies of this Agreement, + but in order to avoid inconsistency the Agreement is copyrighted and may + only be modified in the following manner. The Agreement Steward reserves + the right to publish new versions (including revisions) of this Agreement + from time to time. No one other than the Agreement Steward has the right + to modify this Agreement. IBM is the initial Agreement Steward. IBM may + assign the responsibility to serve as the Agreement Steward to a suitable + separate entity. Each new version of the Agreement will be given a + distinguishing version number. The Program (including Contributions) may + always be distributed subject to the version of the Agreement under which + it was received. In addition, after a new version of the Agreement is + published, Contributor may elect to distribute the Program (including + its Contributions) under the new version. Except as expressly stated in + Sections 2(a) and 2(b) above, Recipient receives no rights or licenses + to the intellectual property of any Contributor under this Agreement, + whether expressly, by implication, estoppel or otherwise. All rights in + the Program not expressly granted under this Agreement are reserved. + + This Agreement is governed by the laws of the State of New York and the + intellectual property laws of the United States of America. No party to + this Agreement will bring a legal action under this Agreement more than + one year after the cause of action arose. Each party waives its rights + to a jury trial in any resulting litigation. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..6d9855f --- /dev/null +++ b/NOTICE @@ -0,0 +1,21 @@ +Apache POI +Copyright 2009 The Apache Software Foundation + +This product includes software developed by +The Apache Software Foundation (http://www.apache.org/). + +This product contains the DOM4J library (http://www.dom4j.org). +Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. + +This product contains parts that were originally based on software from BEA. +Copyright (c) 2000-2003, BEA Systems, <http://www.bea.com/>. + +This product contains W3C XML Schema documents. Copyright 2001-2003 (c) +World Wide Web Consortium (Massachusetts Institute of Technology, European +Research Consortium for Informatics and Mathematics, Keio University) + +This product contains the Piccolo XML Parser for Java +(http://piccolo.sourceforge.net/). Copyright 2002 Yuval Oren. + +This product contains the chunks_parse_cmds.tbl file from the vsdump program. +Copyright (C) 2006-2007 Valek Filippov ([email protected]) diff --git a/README.markdown b/README.markdown new file mode 100644 index 0000000..bd8af54 --- /dev/null +++ b/README.markdown @@ -0,0 +1,87 @@ +[jruby-poi](http://github.com/kameeoze/jruby-poi) +========= + +This little gem provides an alternative interface to the Apache POI java library, for JRuby. For now the API is targeted at wrapping spreadsheets. We may expand this in the future. + +INSTALL +======= + +* gem install jruby-poi + +USAGE +===== +It's pretty simple really, create a POI::Workbook and access its sheets, rows, and cells. You can read from the spreadsheet, save it (as the filename with which you created or as a new spreadsheet via Workbook#save_as). + + require 'poi' + + # given an Excel spreadsheet whose first sheet (Sheet 1) has this data: + # A B C D E + # 1 4 A 2010-01-04 + # 2 3 B =DATE(YEAR($E$1), MONTH($E$1), A2) + # 3 2 C =DATE(YEAR($E$1), MONTH($E$1), A3) + # 4 1 D =DATE(YEAR($E$1), MONTH($E$1), A4) + + workbook = POI::Workbook.open('spreadsheet.xlsx') + sheet = workbook.worksheets["Sheet 1"] + rows = sheet.rows + + # get a cell's value -- returns the value as its proper type, evaluating formulas if need be + rows[0][0].value # => 4.0 + rows[0][1].value # => nil + rows[0][2].value # => 'A' + rows[0][3].value # => nil + rows[0][4].value # => 2010-01-04 as a Date instance + rows[1][4].value # => 2010-01-03 as a Date instance + rows[2][4].value # => 2010-01-02 as a Date instance + rows[3][4].value # => 2010-01-01 as a Date instance + + # you can access a cell in array style as well... these snippets are all equivalent + workbook.sheets[0][2][2] # => 'C' + workbook[0][2][2] # => 'C' + workbook.sheets['Sheet 1'][2][2] # => 'C' + workbook['Sheet 1'][2][2] # => 'C' + + # you can access a cell in 3D cell format too + workbook['Sheet 1!A1'] # => 4.0 + + # you can even refer to ranges of cells + workbook['Sheet 1!A1:A3'] # => [4.0, 3.0, 2.0] + + # if cells E1 - E4 were a named range, you could refer to those cells by its name + # eg. if the cells were named "dates"... + workbook['dates'] # => dates from E1 - E4 + + # to get the Cell instance, instead of its value, just use the Workbook#cell method + workbook.cell('dates') # => cells that contain dates from E1 to E4 + workbook['Sheet 1!A1:A3'] # => cells that contain 4.0, 3.0, and 2.0 + +There's a formatted version of this code [here](http://gist.github.com/557607), but Github doesn't allow embedding script tags in Markdown. Go figure! + +TODO +==== +* fix reading ODS files -- we have a broken spec for this in io_spec.rb +* add APIs for updating cells in a spreadsheet +* create API for non-spreadsheet files + +Contributors +============ + +* [Scott Deming](http://github.com/sdeming) +* [Jason Rogers](http://github.com/jacaetevha) + +Note on Patches/Pull Requests +============================= + +* Fork the project. +* Make your feature addition or bug fix. +* Add tests for it. This is important so I don't break it in a future version unintentionally. +* Commit, do not mess with rakefile, version, or history. + (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull) +* Send me a pull request. + +Copyright +========= + +Copyright (c) 2010 Scott Deming and others. +See NOTICE and LICENSE for details. + diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..bf3ab8b --- /dev/null +++ b/Rakefile @@ -0,0 +1,36 @@ +begin + require 'jeweler' + + Jeweler::Tasks.new do |gemspec| + gemspec.name = "jruby-poi" + gemspec.summary = "Apache POI class library for jruby" + gemspec.description = "A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI." + gemspec.email = ["[email protected]", "[email protected]"] + gemspec.homepage = "http://github.com/sdeming/jruby-poi" + gemspec.authors = ["Scott Deming", "Jason Rogers"] + end +rescue LoadError + puts "Jeweler not available. Install it with: gem install jeweler" +end + +begin + require 'rspec/core/rake_task' + task :default => :spec + + desc "Run all examples" + RSpec::Core::RakeTask.new do |t| + t.pattern = 'specs/**/*.rb' + t.rspec_opts = ['-c'] + end + + desc "Run all examples with RCov" + RSpec::Core::RakeTask.new(:coverage) do |t| + t.pattern = 'specs/**/*.rb' + t.rspec_opts = ['-c'] + t.rcov = true + t.rcov_opts = ['--include', '/lib/', '--exclude', '/gems/,/^specs/,/^.eval.$/'] + end +rescue + puts $!.message + puts "RCov not available. Install it with: gem install rcov (--no-rdoc --no-ri)" +end diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..7deb86f --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.7.1 \ No newline at end of file diff --git a/bin/autospec b/bin/autospec new file mode 100755 index 0000000..3ee978f --- /dev/null +++ b/bin/autospec @@ -0,0 +1,16 @@ +#!/usr/bin/env jruby +# +# This file was generated by Bundler. +# +# The application 'autospec' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'pathname' +ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", + Pathname.new(__FILE__).realpath) + +require 'rubygems' +require 'bundler/setup' + +load Gem.bin_path('rspec-core', 'autospec') diff --git a/bin/htmldiff b/bin/htmldiff new file mode 100755 index 0000000..8cd1f8f --- /dev/null +++ b/bin/htmldiff @@ -0,0 +1,16 @@ +#!/usr/bin/env jruby +# +# This file was generated by Bundler. +# +# The application 'htmldiff' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'pathname' +ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", + Pathname.new(__FILE__).realpath) + +require 'rubygems' +require 'bundler/setup' + +load Gem.bin_path('diff-lcs', 'htmldiff') diff --git a/bin/ldiff b/bin/ldiff new file mode 100755 index 0000000..9b9eaf0 --- /dev/null +++ b/bin/ldiff @@ -0,0 +1,16 @@ +#!/usr/bin/env jruby +# +# This file was generated by Bundler. +# +# The application 'ldiff' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'pathname' +ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", + Pathname.new(__FILE__).realpath) + +require 'rubygems' +require 'bundler/setup' + +load Gem.bin_path('diff-lcs', 'ldiff') diff --git a/bin/rdebug b/bin/rdebug new file mode 100755 index 0000000..b7fc16f --- /dev/null +++ b/bin/rdebug @@ -0,0 +1,16 @@ +#!/usr/bin/env jruby +# +# This file was generated by Bundler. +# +# The application 'rdebug' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'pathname' +ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", + Pathname.new(__FILE__).realpath) + +require 'rubygems' +require 'bundler/setup' + +load Gem.bin_path('ruby-debug', 'rdebug') diff --git a/bin/rspec b/bin/rspec new file mode 100755 index 0000000..b80cb91 --- /dev/null +++ b/bin/rspec @@ -0,0 +1,16 @@ +#!/usr/bin/env jruby +# +# This file was generated by Bundler. +# +# The application 'rspec' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require 'pathname' +ENV['BUNDLE_GEMFILE'] ||= File.expand_path("../../Gemfile", + Pathname.new(__FILE__).realpath) + +require 'rubygems' +require 'bundler/setup' + +load Gem.bin_path('rspec-core', 'rspec') diff --git a/jruby-poi.gemspec b/jruby-poi.gemspec new file mode 100644 index 0000000..5182d5b --- /dev/null +++ b/jruby-poi.gemspec @@ -0,0 +1,86 @@ +# Generated by jeweler +# DO NOT EDIT THIS FILE DIRECTLY +# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' +# -*- encoding: utf-8 -*- + +Gem::Specification.new do |s| + s.name = %q{jruby-poi} + s.version = "0.7.1" + + s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= + s.authors = ["Scott Deming", "Jason Rogers"] + s.date = %q{2011-03-31} + s.description = %q{A rubyesque library for manipulating spreadsheets and other document types for jruby, using Apache POI.} + s.email = ["[email protected]", "[email protected]"] + s.executables = ["autospec", "htmldiff", "ldiff", "rdebug", "rspec"] + s.extra_rdoc_files = [ + "LICENSE", + "README.markdown" + ] + s.files = [ + "Gemfile", + "Gemfile.lock", + "LICENSE", + "NOTICE", + "README.markdown", + "Rakefile", + "VERSION", + "bin/autospec", + "bin/htmldiff", + "bin/ldiff", + "bin/rdebug", + "bin/rspec", + "jruby-poi.gemspec", + "lib/ooxml-lib/dom4j-1.6.1.jar", + "lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar", + "lib/ooxml-lib/xmlbeans-2.3.0.jar", + "lib/poi-3.6-20091214.jar", + "lib/poi-contrib-3.6-20091214.jar", + "lib/poi-examples-3.6-20091214.jar", + "lib/poi-ooxml-3.6-20091214.jar", + "lib/poi-ooxml-schemas-3.6-20091214.jar", + "lib/poi-scratchpad-3.6-20091214.jar", + "lib/poi.rb", + "lib/poi/workbook.rb", + "lib/poi/workbook/area.rb", + "lib/poi/workbook/cell.rb", + "lib/poi/workbook/named_range.rb", + "lib/poi/workbook/row.rb", + "lib/poi/workbook/workbook.rb", + "lib/poi/workbook/worksheet.rb", + "spec_debug.sh", + "specs/data/simple_with_picture.ods", + "specs/data/simple_with_picture.xls", + "specs/data/spreadsheet.ods", + "specs/data/timesheet.xlsx", + "specs/data/various_samples.xlsx", + "specs/facade_spec.rb", + "specs/io_spec.rb", + "specs/spec_helper.rb", + "specs/support/java/jrubypoi/MockOutputStream.java", + "specs/support/java/support.jar", + "specs/support/matchers/cell_matcher.rb", + "specs/workbook_spec.rb", + "specs/writing_spec.rb" + ] + s.homepage = %q{http://github.com/sdeming/jruby-poi} + s.require_paths = ["lib"] + s.rubygems_version = %q{1.5.1} + s.summary = %q{Apache POI class library for jruby} + + if s.respond_to? :specification_version then + s.specification_version = 3 + + if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then + s.add_development_dependency(%q<rspec>, [">= 0"]) + s.add_development_dependency(%q<ruby-debug>, [">= 0"]) + else + s.add_dependency(%q<rspec>, [">= 0"]) + s.add_dependency(%q<ruby-debug>, [">= 0"]) + end + else + s.add_dependency(%q<rspec>, [">= 0"]) + s.add_dependency(%q<ruby-debug>, [">= 0"]) + end +end + diff --git a/lib/ooxml-lib/dom4j-1.6.1.jar b/lib/ooxml-lib/dom4j-1.6.1.jar new file mode 100644 index 0000000..c8c4dbb Binary files /dev/null and b/lib/ooxml-lib/dom4j-1.6.1.jar differ diff --git a/lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar b/lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar new file mode 100644 index 0000000..0d6d374 Binary files /dev/null and b/lib/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar differ diff --git a/lib/ooxml-lib/xmlbeans-2.3.0.jar b/lib/ooxml-lib/xmlbeans-2.3.0.jar new file mode 100644 index 0000000..ccd8163 Binary files /dev/null and b/lib/ooxml-lib/xmlbeans-2.3.0.jar differ diff --git a/lib/poi-3.6-20091214.jar b/lib/poi-3.6-20091214.jar new file mode 100644 index 0000000..9972d97 Binary files /dev/null and b/lib/poi-3.6-20091214.jar differ diff --git a/lib/poi-contrib-3.6-20091214.jar b/lib/poi-contrib-3.6-20091214.jar new file mode 100644 index 0000000..07403a9 Binary files /dev/null and b/lib/poi-contrib-3.6-20091214.jar differ diff --git a/lib/poi-examples-3.6-20091214.jar b/lib/poi-examples-3.6-20091214.jar new file mode 100644 index 0000000..988e39e Binary files /dev/null and b/lib/poi-examples-3.6-20091214.jar differ diff --git a/lib/poi-ooxml-3.6-20091214.jar b/lib/poi-ooxml-3.6-20091214.jar new file mode 100644 index 0000000..c986646 Binary files /dev/null and b/lib/poi-ooxml-3.6-20091214.jar differ diff --git a/lib/poi-ooxml-schemas-3.6-20091214.jar b/lib/poi-ooxml-schemas-3.6-20091214.jar new file mode 100644 index 0000000..5b79f02 Binary files /dev/null and b/lib/poi-ooxml-schemas-3.6-20091214.jar differ diff --git a/lib/poi-scratchpad-3.6-20091214.jar b/lib/poi-scratchpad-3.6-20091214.jar new file mode 100644 index 0000000..1a01b2b Binary files /dev/null and b/lib/poi-scratchpad-3.6-20091214.jar differ diff --git a/lib/poi.rb b/lib/poi.rb new file mode 100644 index 0000000..12c7bdc --- /dev/null +++ b/lib/poi.rb @@ -0,0 +1,14 @@ +JRUBY_POI_LIB_PATH=File.expand_path(File.dirname(__FILE__)) + +# Java +require 'java' +require File.join(JRUBY_POI_LIB_PATH, 'poi-3.6-20091214.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-3.6-20091214.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-ooxml-schemas-3.6-20091214.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-scratchpad-3.6-20091214.jar') +require File.join(JRUBY_POI_LIB_PATH, 'poi-contrib-3.6-20091214.jar') +require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'xmlbeans-2.3.0.jar') +require File.join(JRUBY_POI_LIB_PATH, 'ooxml-lib', 'dom4j-1.6.1.jar') + +# Ruby +require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook') diff --git a/lib/poi/workbook.rb b/lib/poi/workbook.rb new file mode 100644 index 0000000..8356f4b --- /dev/null +++ b/lib/poi/workbook.rb @@ -0,0 +1,41 @@ +module POI + AREA_REF = org.apache.poi.ss.util.AreaReference + CELL_REF = org.apache.poi.ss.util.CellReference + + def self.Facade(delegate, java_class) + cls = Class.new + java_class.java_class.java_instance_methods.select{|e| e.public?}.each do | method | + args = method.arity.times.collect{|i| "arg#{i}"}.join(", ") + method_name = method.name.gsub(/([A-Z])/){|e| "_#{e.downcase}"} + code = "def #{method_name}(#{args}); #{delegate}.#{method.name}(#{args}); end" + + if method_name =~ /^get_[a-z]/ + alias_method_name = method_name.sub('get_', '') + code += "\nalias :#{alias_method_name} :#{method_name}" + if method.return_type.to_s == 'boolean' + code += "\nalias :#{alias_method_name}? :#{method_name}" + end + elsif method_name =~ /^set_[a-z]/ && method.arity == 1 + alias_method_name = "#{method_name.sub('set_', '')}" + code += "\nalias :#{alias_method_name}= :#{method_name}" + if method.argument_types.first.to_s == 'boolean' + code += "\ndef #{alias_method_name}!; #{alias_method_name} = true; end" + end + elsif method.return_type.to_s == 'boolean' && method_name =~ /is_/ + code += "\nalias :#{method_name.sub('is_', '')}? :#{method_name}" + elsif method.return_type.nil? && (method.argument_types.nil? || method.argument_types.empty?) + code += "\nalias :#{method_name}! :#{method_name}" + end + + cls.class_eval(code, __FILE__, __LINE__) + end + cls + end +end + +require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook', 'area') +require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook', 'named_range') +require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook', 'workbook') +require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook', 'worksheet') +require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook', 'row') +require File.join(JRUBY_POI_LIB_PATH, 'poi', 'workbook', 'cell') diff --git a/lib/poi/workbook/area.rb b/lib/poi/workbook/area.rb new file mode 100644 index 0000000..ed1015c --- /dev/null +++ b/lib/poi/workbook/area.rb @@ -0,0 +1,81 @@ +module POI + class Area + def initialize reference + @ref = reference + end + + def in workbook + if single_cell_reference? + ref = area.all_referenced_cells.first + return [workbook.single_cell ref] + end + + begin + by_column = {} + # refs = area.all_referenced_cells + # slices = refs.enum_slice(refs.length/15) + # slices.collect do |cell_refs| + # Thread.start do + # cell_refs.each do |cell_ref| + # first = workbook.worksheets[cell_ref.sheet_name].first_row + # last = workbook.worksheets[cell_ref.sheet_name].last_row + # next unless cell_ref.row >= first && cell_ref.row <= last + # + # # ref = POI::CELL_REF.new(c.format_as_string) + # cell = workbook.single_cell cell_ref + # (by_column[cell_ref.cell_ref_parts.collect.last] ||= []) << cell + # end + # end + # end.each {|t| t.join} + + area.all_referenced_cells.each do |cell_ref| + first = workbook.worksheets[cell_ref.sheet_name].first_row + last = workbook.worksheets[cell_ref.sheet_name].last_row + next unless cell_ref.row >= first && cell_ref.row <= last + + # ref = POI::CELL_REF.new(c.format_as_string) + cell = workbook.single_cell cell_ref + (by_column[cell_ref.cell_ref_parts.collect.last] ||= []) << cell + end + + by_column.each do |key, cells| + by_column[key] = cells.compact + end + + if by_column.length == 1 + by_column.values.flatten + else + by_column + end + rescue + [] + end + end + + def single_cell_reference? + area.single_cell? #@ref == getFirstCell.formatAsString rescue false + end + + private + def area + @area ||= new_area_reference + end + + def new_area_reference + begin + return POI::AREA_REF.new(@ref) + rescue + # not a valid reference, so proceed through to see if it's a column-based reference + end + sheet_parts = @ref.split('!') + area_parts = sheet_parts.last.split(':') + area_start = "#{sheet_parts.first}!#{area_parts.first}" + area_end = area_parts.last + begin + POI::AREA_REF.getWholeColumn(area_start, area_end) + rescue + raise "could not determine area reference for #{@ref}: #{$!.message}" + end + end + end +end \ No newline at end of file diff --git a/lib/poi/workbook/cell.rb b/lib/poi/workbook/cell.rb new file mode 100644 index 0000000..50dab15 --- /dev/null +++ b/lib/poi/workbook/cell.rb @@ -0,0 +1,175 @@ +module POI + class Cells + include Enumerable + + def initialize(row) + @row = row + @poi_row = row.poi_row + @cells = {} + end + + def [](index) + @cells[index] ||= Cell.new(@poi_row.cell(index) || @poi_row.create_cell(index), @row) + end + + def size + @poi_row.physical_number_of_cells + end + + def each + it = @poi_row.cell_iterator + yield Cell.new(it.next, @row) while it.has_next + end + end + + class Cell < Facade(:poi_cell, org.apache.poi.ss.usermodel.Cell) + DATE_UTIL = Java::org.apache.poi.ss.usermodel.DateUtil + CELL = Java::org.apache.poi.ss.usermodel.Cell + CELL_VALUE = Java::org.apache.poi.ss.usermodel.CellValue + CELL_TYPE_BLANK = CELL::CELL_TYPE_BLANK + CELL_TYPE_BOOLEAN = CELL::CELL_TYPE_BOOLEAN + CELL_TYPE_ERROR = CELL::CELL_TYPE_ERROR + CELL_TYPE_FORMULA = CELL::CELL_TYPE_FORMULA + CELL_TYPE_NUMERIC = CELL::CELL_TYPE_NUMERIC + CELL_TYPE_STRING = CELL::CELL_TYPE_STRING + + def initialize(cell, row) + @cell = cell + @row = row + end + + def <=> other + return 1 if other.nil? + return self.index <=> other.index + end + + # This is NOT an inexpensive operation. The purpose of this method is merely to get more information + # out of cell when one thinks the value returned is incorrect. It may have more value in development + # than in production. + def error_value + if poi_cell.cell_type == CELL_TYPE_ERROR + error_value_from(poi_cell.error_cell_value) + elsif poi_cell.cell_type == CELL_TYPE_FORMULA && + poi_cell.cached_formula_result_type == CELL_TYPE_ERROR + + # breaks Law of Demeter by reaching into the Row's Worksheet, but it makes sense to do in this case + value_of(@row.worksheet.workbook.formula_evaluator.evaluate(poi_cell)) + else + nil + end + end + + # returns the formula for this Cell if it has one, otherwise nil + def formula_value + poi_cell.cell_type == CELL_TYPE_FORMULA ? poi_cell.cell_formula : nil + end + + def value + return nil if poi_cell.nil? + value_of(cell_value_for_type(poi_cell.cell_type)) + end + + def formula= new_value + poi_cell.cell_formula = new_value + @row.worksheet.workbook.on_formula_update self + self + end + + def formula + poi_cell.cell_formula + end + + def value= new_value + set_cell_value new_value + if new_value.nil? + @row.worksheet.workbook.on_delete self + else + @row.worksheet.workbook.on_update self + end + self + end + + def comment + poi_cell.cell_comment + end + + def index + poi_cell.column_index + end + + # Get the String representation of this Cell's value. + # + # If this Cell is a formula you can pass a false to this method and + # get the formula instead of the String representation. + def to_s(evaluate_formulas=true) + return '' if poi_cell.nil? + + if poi_cell.cell_type == CELL_TYPE_FORMULA && evaluate_formulas == false + formula_value + else + value.to_s + end + end + + # returns the underlying org.apache.poi.ss.usermodel.Cell + def poi_cell + @cell + end + + # :cell_style= comes from the Façade superclass + alias :style= :cell_style= + + def style! options + self.style = @row.worksheet.workbook.create_style(options) + end + + private + def value_of(cell_value) + return nil if cell_value.nil? + + case cell_value.cell_type + when CELL_TYPE_BLANK: nil + when CELL_TYPE_BOOLEAN: cell_value.boolean_value + when CELL_TYPE_ERROR: error_value_from(cell_value.error_value) + when CELL_TYPE_NUMERIC: numeric_value_from(cell_value) + when CELL_TYPE_STRING: cell_value.string_value + else + raise "unhandled cell type[#{cell_value.cell_type}]" + end + end + + def cell_value_for_type(cell_type) + return nil if cell_type.nil? + begin + case cell_type + when CELL_TYPE_BLANK: nil + when CELL_TYPE_BOOLEAN: CELL_VALUE.value_of(poi_cell.boolean_cell_value) + when CELL_TYPE_FORMULA: cell_value_for_type(poi_cell.cached_formula_result_type) + when CELL_TYPE_STRING: CELL_VALUE.new(poi_cell.string_cell_value) + when CELL_TYPE_ERROR, CELL_TYPE_NUMERIC: CELL_VALUE.new(poi_cell.numeric_cell_value) + else + raise "unhandled cell type[#{poi_cell.cell_type}]" + end + rescue + nil + end + end + + def error_value_from(cell_value) + org.apache.poi.ss.usermodel.ErrorConstants.text(cell_value) + end + + def formula_evaluator_for(workbook) + workbook.creation_helper.create_formula_evaluator + end + + def numeric_value_from(cell_value) + if DATE_UTIL.cell_date_formatted(poi_cell) + Date.parse(DATE_UTIL.get_java_date(cell_value.number_value).to_s) + else + cell_value.number_value + end + end + end +end + diff --git a/lib/poi/workbook/named_range.rb b/lib/poi/workbook/named_range.rb new file mode 100644 index 0000000..03ef400 --- /dev/null +++ b/lib/poi/workbook/named_range.rb @@ -0,0 +1,30 @@ +module POI + class NamedRange + + # takes an instance of org.apache.poi.ss.usermodel.Name, and a POI::Workbook + def initialize name, workbook + @name = name + @workbook = workbook + end + + def name + @name.name_name + end + + def sheet + @workbook.worksheets[@name.sheet_name] + end + + def formula + @name.refers_to_formula + end + + def cells + @name.is_deleted ? [] : [@workbook.cell(formula)].flatten + end + + def values + cells.collect{|c| c.value} + end + end +end \ No newline at end of file diff --git a/lib/poi/workbook/row.rb b/lib/poi/workbook/row.rb new file mode 100644 index 0000000..27feb8a --- /dev/null +++ b/lib/poi/workbook/row.rb @@ -0,0 +1,58 @@ +module POI + class Rows + include Enumerable + + def initialize(worksheet) + @worksheet = worksheet + @poi_worksheet = worksheet.poi_worksheet + @rows = {} + end + + def [](index) + @rows[index] ||= Row.new(@poi_worksheet.row(index) || @poi_worksheet.create_row(index), @worksheet) + end + + def size + @poi_worksheet.physical_number_of_rows + end + + def each + it = @poi_worksheet.row_iterator + yield Row.new(it.next, @worksheet) while it.has_next + end + end + + class Row < Facade(:poi_row, org.apache.poi.ss.usermodel.Row) + def initialize(row, worksheet) + @row = row + @worksheet = worksheet + end + + def [](index) + return nil if poi_row.nil? + cells[index] + end + + def cells + @cells ||= Cells.new(self) + end + + def index + return nil if poi_row.nil? + poi_row.row_num + end + + # def height_in_points= num + # set_height_in_points num.to_f + # end + + def poi_row + @row + end + + def worksheet + @worksheet + end + end +end + diff --git a/lib/poi/workbook/workbook.rb b/lib/poi/workbook/workbook.rb new file mode 100644 index 0000000..266b7f1 --- /dev/null +++ b/lib/poi/workbook/workbook.rb @@ -0,0 +1,262 @@ +require 'tmpdir' +require 'stringio' +require 'java' + +module POI + class Workbook < Facade(:poi_workbook, org.apache.poi.ss.usermodel.Workbook) + FONT = org.apache.poi.ss.usermodel.Font + FONT_CONSTANTS = Hash[*FONT.constants.map{|e| [e.downcase.to_sym, FONT.const_get(e)]}.flatten] + + CELL_STYLE = org.apache.poi.ss.usermodel.CellStyle + CELL_STYLE_CONSTANTS = Hash[*CELL_STYLE.constants.map{|e| [e.downcase.to_sym, CELL_STYLE.const_get(e)]}.flatten] + + INDEXED_COLORS = org.apache.poi.ss.usermodel.IndexedColors + INDEXED_COLORS_CONSTANTS = Hash[*INDEXED_COLORS.constants.map{|e| [e.downcase.to_sym, INDEXED_COLORS.const_get(e)]}.flatten] + + def self.open(filename_or_stream) + name, stream = if filename_or_stream.kind_of?(java.io.InputStream) + [File.join(Dir.tmpdir, "spreadsheet.xlsx"), filename_or_stream] + elsif filename_or_stream.kind_of?(IO) || StringIO === filename_or_stream || filename_or_stream.respond_to?(:read) + # NOTE: the String.unpack here can be very inefficient on large files + [File.join(Dir.tmpdir, "spreadsheet.xlsx"), java.io.ByteArrayInputStream.new(filename_or_stream.read.unpack('c*').to_java(:byte))] + else + raise Exception, "FileNotFound" unless File.exists?( filename_or_stream ) + [filename_or_stream, java.io.FileInputStream.new(filename_or_stream)] + end + instance = self.new(name, stream) + if block_given? + result = yield instance + return result + end + instance + end + + def self.create(filename) + self.new(filename, nil) + end + + attr_reader :filename + + def initialize(filename, io_stream) + @filename = filename + @workbook = io_stream ? org.apache.poi.ss.usermodel.WorkbookFactory.create(io_stream) : org.apache.poi.xssf.usermodel.XSSFWorkbook.new + end + + def formula_evaluator + @formula_evaluator ||= @workbook.creation_helper.create_formula_evaluator + end + + def save + save_as(@filename) + end + + def save_as(filename) + output = output_stream filename + begin + @workbook.write(output) + ensure + output.close + end + end + + def output_stream name + java.io.FileOutputStream.new(name) + end + + def close + #noop + end + + def create_sheet name='New Sheet' + # @workbook.createSheet name + worksheets[name] + end + + def create_style options={} + font = @workbook.createFont + set_value( font, :font_height_in_points, options ) do | value | + value.to_i + end + set_value font, :bold_weight, options, FONT_CONSTANTS + set_value font, :color, options, INDEXED_COLORS_CONSTANTS do | value | + value.index + end + + style = @workbook.createCellStyle + [:alignment, :vertical_alignment, :fill_pattern, :border_right, :border_left, :border_top, :border_bottom].each do | sym | + set_value style, sym, options, CELL_STYLE_CONSTANTS do | value | + value.to_i + end + end + [:right_border_color, :left_border_color, :top_border_color, :bottom_border_color, :fill_foreground_color, :fill_background_color].each do | sym | + set_value( style, sym, options, INDEXED_COLORS_CONSTANTS ) do | value | + value.index + end + end + [:hidden, :locked, :wrap_text].each do | sym | + set_value style, sym, options + end + [:rotation, :indentation].each do | sym | + set_value( style, sym, options ) do | value | + value.to_i + end + end + set_value( style, :data_format, options ) do |value| + @workbook.create_data_format.getFormat(value) + end + style.font = font + style + end + + def set_value on, value_sym, from, using=nil + return on unless from.has_key?(value_sym) + value = if using + using[from[value_sym]] + else + from[value_sym] + end + value = yield value if block_given? + on.send("set_#{value_sym}", value) + on + end + + def worksheets + @worksheets ||= Worksheets.new(self) + end + + def named_ranges + @named_ranges ||= ([email protected]_of_names).collect do | idx | + NamedRange.new @workbook.name_at(idx), self + end + end + + # reference can be a Fixnum, referring to the 0-based sheet or + # a String which is the sheet name or a cell reference. + # + # If a cell reference is passed the value of that cell is returned. + # + # If the reference refers to a contiguous range of cells an Array of values will be returned. + # + # If the reference refers to a multiple columns a Hash of values will be returned by column name. + def [](reference) + if Fixnum === reference + return worksheets[reference] + end + + if sheet = worksheets.detect{|e| e.name == reference} + return sheet.poi_worksheet.nil? ? nil : sheet + end + + cell = cell(reference) + if Array === cell + cell.collect{|e| e.value} + elsif Hash === cell + values = {} + cell.each_pair{|column_name, cells| values[column_name] = cells.collect{|e| e.value}} + values + else + cell.value + end + end + + # takes a String in the form of a 3D cell reference and returns the Cell (eg. "Sheet 1!A1") + # + # If the reference refers to a contiguous range of cells an array of Cells will be returned + def cell reference + # if the reference is to a named range of cells, get that range and return it + if named_range = named_ranges.detect{|e| e.name == reference} + cells = named_range.cells.compact + if cells.empty? + return nil + else + return cells.length == 1 ? cells.first : cells + end + end + + # check if the named_range is a full column reference + if column_reference?(named_range) + return all_cells_in_column named_range.formula + end + + # if the reference is to an area of cells, get all the cells in that area and return them + cells = cells_in_area(reference) + unless cells.empty? + return cells.length == 1 ? cells.first : cells + end + + if column_reference?(reference) + return all_cells_in_column reference + end + + ref = POI::CELL_REF.new(reference) + single_cell ref + end + + # ref is a POI::CELL_REF instance + def single_cell ref + if ref.sheet_name.nil? + raise 'cell references at the workbook level must include a sheet reference (eg. Sheet1!A1)' + else + worksheets[ref.sheet_name][ref.row][ref.col] + end + end + + def cells_in_area reference + area = Area.new(reference) + area.in(self) + end + + def poi_workbook + @workbook + end + + def on_update cell + #clear_all_formula_results + #formula_evaluator.notify_update_cell cell.poi_cell + end + + def on_formula_update cell + #clear_all_formula_results + formula_evaluator.notify_set_formula cell.poi_cell + formula_evaluator.evaluate_formula_cell(cell.poi_cell) + end + + def on_delete cell + #clear_all_formula_results + formula_evaluator.notify_delete_cell cell.poi_cell + end + + def clear_all_formula_results + formula_evaluator.clear_all_cached_result_values + end + + def all_cells_in_column reference + sheet_parts = reference.split('!') + area_parts = sheet_parts.last.split(':') + area_start = "#{sheet_parts.first}!#{area_parts.first}" + area_end = area_parts.last + + area = org.apache.poi.ss.util.AreaReference.getWholeColumn(area_start, area_end) + full_ref = "#{area.first_cell.format_as_string}:#{area.last_cell.format_as_string}" + Area.new(full_ref).in(self) + # cell_reference = org.apache.poi.ss.util.CellReference.new( reference + "1" ) + # column = cell_reference.get_col + # sheet = cell_reference.get_sheet_name + # worksheets[sheet].rows.collect{|row| row[column]} + end + + private + def column_reference? named_range_or_reference + return false if named_range_or_reference.nil? + + reference = named_range_or_reference + if NamedRange === named_range_or_reference + reference = named_range_or_reference.formula + end + cell_reference = reference.split('!', 2).last + beginning, ending = cell_reference.split(':') + !(beginning =~ /\d/ || (ending.nil? ? false : ending =~ /\d/)) + end + end +end + diff --git a/lib/poi/workbook/worksheet.rb b/lib/poi/workbook/worksheet.rb new file mode 100644 index 0000000..2732072 --- /dev/null +++ b/lib/poi/workbook/worksheet.rb @@ -0,0 +1,78 @@ +module POI + class Worksheets + include Enumerable + + def initialize(workbook) + @workbook = workbook + @poi_workbook = workbook.poi_workbook + end + + def [](index_or_name) + worksheet = case + when index_or_name.kind_of?(Numeric) + @poi_workbook.sheet_at(index_or_name) || @poi_workbook.create_sheet + else + @poi_workbook.get_sheet(index_or_name) || @poi_workbook.create_sheet(index_or_name) + end + Worksheet.new(worksheet, @workbook) + end + + def size + @poi_workbook.number_of_sheets + end + + def each + (0...size).each { |i| yield Worksheet.new(@poi_workbook.sheet_at(i), @workbook) } + end + end + + class Worksheet < Facade(:poi_worksheet, org.apache.poi.ss.usermodel.Sheet) + + def initialize(worksheet, workbook) + @worksheet = worksheet + @workbook = workbook + end + + def name + @worksheet.sheet_name + end + + def first_row + @worksheet.first_row_num + end + + def last_row + @worksheet.last_row_num + end + + def rows + @rows ||= Rows.new(self) + end + + # Accepts a Fixnum or a String as the row_index + # + # row_index as Fixnum: returns the 0-based row + # + # row_index as String: assumes a cell reference within this sheet + # if the value of the reference is non-nil the value is returned, + # otherwise the referenced cell is returned + def [](row_index) + if Fixnum === row_index + rows[row_index] + else + ref = org.apache.poi.ss.util.CellReference.new(row_index) + cell = rows[ref.row][ref.col] + cell && cell.value ? cell.value : cell + end + end + + def poi_worksheet + @worksheet + end + + def workbook + @workbook + end + end +end + diff --git a/spec_debug.sh b/spec_debug.sh new file mode 100755 index 0000000..1266384 --- /dev/null +++ b/spec_debug.sh @@ -0,0 +1,32 @@ +#!/bin/sh +#set -x +RUBY_DIR=$(dirname $(which ruby))/.. +if [[ ${RUBY_DIR} == *1.6.* ]] +then + RUBYGEMS_DIR=${RUBY_DIR}/lib/ruby/gems/jruby/gems +else + RUBYGEMS_DIR=${RUBY_DIR}/lib/ruby/gems/1.8/gems +fi + +GEM_COLUMNIZE=$(ls -1d $RUBYGEMS_DIR/columnize*/lib | head -1 | /usr/bin/ruby -e 'print File.expand_path($stdin.read)') +GEM_RUBY_DEBUG_BASE=$(ls -1d $RUBYGEMS_DIR/ruby-debug-base-*/lib | head -1 | /usr/bin/ruby -e 'print File.expand_path($stdin.read)') +GEM_RUBY_DEBUG_CLI=$(ls -1d $RUBYGEMS_DIR/ruby-debug-*/cli | head -1 | /usr/bin/ruby -e 'print File.expand_path($stdin.read)') +GEM_SOURCES=$(ls -1d $RUBYGEMS_DIR/sources-*/lib | head -1 | /usr/bin/ruby -e 'print File.expand_path($stdin.read)') + +echo "RUBYGEMS_DIR: ${RUBYGEMS_DIR}" +echo "GEM_SOURCES: ${GEM_SOURCES}" +echo "GEM_COLUMNIZE: ${GEM_COLUMNIZE}" +echo "GEM_RUBY_DEBUG_CLI: ${GEM_RUBY_DEBUG_CLI}" +echo "GEM_RUBY_DEBUG_BASE: ${GEM_RUBY_DEBUG_BASE}" + +runner="ruby --client \ +-I${GEM_COLUMNIZE} \ +-I${GEM_RUBY_DEBUG_BASE} \ +-I${GEM_RUBY_DEBUG_CLI} \ +-I${GEM_SOURCES} \ +-rubygems -S" + +cmd="bundle exec rdebug rspec -c $*" +#cmd="irb" + +$runner $cmd diff --git a/specs/data/simple_with_picture.ods b/specs/data/simple_with_picture.ods new file mode 100644 index 0000000..eb9b188 Binary files /dev/null and b/specs/data/simple_with_picture.ods differ diff --git a/specs/data/simple_with_picture.xls b/specs/data/simple_with_picture.xls new file mode 100644 index 0000000..01acf4d Binary files /dev/null and b/specs/data/simple_with_picture.xls differ diff --git a/specs/data/spreadsheet.ods b/specs/data/spreadsheet.ods new file mode 100644 index 0000000..ce8d8ae Binary files /dev/null and b/specs/data/spreadsheet.ods differ diff --git a/specs/data/timesheet.xlsx b/specs/data/timesheet.xlsx new file mode 100644 index 0000000..f4640b2 Binary files /dev/null and b/specs/data/timesheet.xlsx differ diff --git a/specs/data/various_samples.xlsx b/specs/data/various_samples.xlsx new file mode 100644 index 0000000..ec5d456 Binary files /dev/null and b/specs/data/various_samples.xlsx differ diff --git a/specs/facade_spec.rb b/specs/facade_spec.rb new file mode 100644 index 0000000..4b5e4da --- /dev/null +++ b/specs/facade_spec.rb @@ -0,0 +1,48 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') + +describe "POI.Facade" do + it "should create specialized methods for boolean methods, getters, and setters" do + book = POI::Workbook.create('foo.xlsx') + sheet = book.create_sheet + sheet.respond_to?(:column_broken?).should be_true + sheet.respond_to?(:column_hidden?).should be_true + sheet.respond_to?(:display_formulas?).should be_true + sheet.respond_to?(:display_gridlines?).should be_true + sheet.respond_to?(:selected?).should be_true + sheet.respond_to?(:column_breaks).should be_true + sheet.respond_to?(:column_break=).should be_true + sheet.respond_to?(:autobreaks?).should be_true + sheet.respond_to?(:autobreaks=).should be_true + sheet.respond_to?(:autobreaks!).should be_true + sheet.respond_to?(:column_broken?).should be_true + sheet.respond_to?(:fit_to_page).should be_true + sheet.respond_to?(:fit_to_page?).should be_true + sheet.respond_to?(:fit_to_page=).should be_true + sheet.respond_to?(:fit_to_page!).should be_true + + sheet.respond_to?(:array_formula).should_not be_true + sheet.respond_to?(:array_formula=).should_not be_true + + row = sheet[0] + row.respond_to?(:first_cell_num).should be_true + row.respond_to?(:height).should be_true + row.respond_to?(:height=).should be_true + row.respond_to?(:height_in_points).should be_true + row.respond_to?(:height_in_points=).should be_true + row.respond_to?(:zero_height?).should be_true + row.respond_to?(:zero_height!).should be_true + row.respond_to?(:zero_height=).should be_true + + cell = row[0] + cell.respond_to?(:boolean_cell_value).should be_true + cell.respond_to?(:boolean_cell_value?).should be_true + cell.respond_to?(:cached_formula_result_type).should be_true + cell.respond_to?(:cell_error_value=).should be_true + cell.respond_to?(:cell_value=).should be_true + cell.respond_to?(:hyperlink=).should be_true + cell.respond_to?(:cell_value!).should be_true + cell.respond_to?(:remove_cell_comment!).should be_true + cell.respond_to?(:cell_style).should be_true + cell.respond_to?(:cell_style=).should be_true + end +end \ No newline at end of file diff --git a/specs/io_spec.rb b/specs/io_spec.rb new file mode 100644 index 0000000..d1d247a --- /dev/null +++ b/specs/io_spec.rb @@ -0,0 +1,69 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') + +describe POI::Workbook do + before :each do + @mock_output_stream = nil + class POI::Workbook + def mock_output_stream name + @mock_output_stream ||= Java::jrubypoi.MockOutputStream.new name + @mock_output_stream + end + + alias_method :original_output_stream, :output_stream unless method_defined?(:original_output_stream) + alias_method :output_stream, :mock_output_stream + end + end + + after :each do + @mock_output_stream = nil + class POI::Workbook + alias_method :output_stream, :original_output_stream + end + end + + it "should read an xlsx file" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = nil + lambda { book = POI::Workbook.open(name) }.should_not raise_exception + book.should be_kind_of POI::Workbook + end + + it "should read an xls file" do + name = TestDataFile.expand_path("simple_with_picture.xls") + book = nil + lambda { book = POI::Workbook.open(name) }.should_not raise_exception + book.should be_kind_of POI::Workbook + end + + it "should read an ods file" do + name = TestDataFile.expand_path("spreadsheet.ods") + book = nil + lambda { book = POI::Workbook.open(name) }.should_not raise_exception + book.should be_kind_of POI::Workbook + end + + it "should write an open workbook" do + name = TestDataFile.expand_path("various_samples.xlsx") + POI::Workbook.open(name) do |book| + lambda { book.save }.should_not raise_exception + verify_mock_output_stream book.instance_variable_get("@mock_output_stream"), name + end + end + + it "should write an open workbook to a new file" do + name = TestDataFile.expand_path("various_samples.xlsx") + new_name = TestDataFile.expand_path("saved-as.xlsx") + + POI::Workbook.open(name) do |book| + @mock_output_stream.should be_nil + lambda { book.save_as(new_name) }.should_not raise_exception + verify_mock_output_stream book.instance_variable_get("@mock_output_stream"), new_name + end + end + + def verify_mock_output_stream mock_output_stream, name + mock_output_stream.should_not be_nil + name.should == mock_output_stream.name + true.should == mock_output_stream.write_called + end +end diff --git a/specs/spec_helper.rb b/specs/spec_helper.rb new file mode 100644 index 0000000..9fdc232 --- /dev/null +++ b/specs/spec_helper.rb @@ -0,0 +1,13 @@ +require 'rspec' +require File.expand_path(File.join(File.dirname(__FILE__), '..', 'lib', 'poi')) +Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f} +require File.join(File.dirname(__FILE__), "support", "java", "support.jar") + +class TestDataFile + def self.expand_path(name) + File.expand_path(File.join(File.dirname(__FILE__), 'data', name)) + end +end + +RSpec.configure do |config| +end diff --git a/specs/support/java/jrubypoi/MockOutputStream.java b/specs/support/java/jrubypoi/MockOutputStream.java new file mode 100644 index 0000000..5f6ad1f --- /dev/null +++ b/specs/support/java/jrubypoi/MockOutputStream.java @@ -0,0 +1,24 @@ +package jrubypoi; +import java.io.*; + +public class MockOutputStream extends OutputStream { + public String name; + public boolean write_called; + + public MockOutputStream(String name) { + this.name = name; + this.write_called = false; + } + + public void write(int b) throws IOException { + this.write_called = true; + } + + public void write(byte[] b) throws IOException { + this.write_called = true; + } + + public void write(byte[] b, int offset, int length) throws IOException { + this.write_called = true; + } +} \ No newline at end of file diff --git a/specs/support/java/support.jar b/specs/support/java/support.jar new file mode 100644 index 0000000..a33ca4e Binary files /dev/null and b/specs/support/java/support.jar differ diff --git a/specs/support/matchers/cell_matcher.rb b/specs/support/matchers/cell_matcher.rb new file mode 100644 index 0000000..3b90c8b --- /dev/null +++ b/specs/support/matchers/cell_matcher.rb @@ -0,0 +1,17 @@ +RSpec::Matchers.define :equal_at_cell do |expected, row, col| + match do |actual| + actual == expected + end + + failure_message_for_should do |actual| + "expected #{actual} to equal #{expected} (row:#{row}, cell:#{col})" + end + + failure_message_for_should_not do |actual| + "expected #{actual} not to equal #{expected} (row:#{row}, cell:#{col})" + end + + description do + "to equal #{expected}" + end +end \ No newline at end of file diff --git a/specs/workbook_spec.rb b/specs/workbook_spec.rb new file mode 100644 index 0000000..df67355 --- /dev/null +++ b/specs/workbook_spec.rb @@ -0,0 +1,369 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') +require 'date' +require 'stringio' + +describe POI::Workbook do + it "should open a workbook and allow access to its worksheets" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book.worksheets.size.should == 5 + book.filename.should == name + end + + it "should be able to create a Workbook from an IO object" do + content = StringIO.new(open(TestDataFile.expand_path("various_samples.xlsx"), 'rb'){|f| f.read}) + book = POI::Workbook.open(content) + book.worksheets.size.should == 5 + book.filename.should =~ /spreadsheet.xlsx$/ + end + + it "should be able to create a Workbook from a Java input stream" do + content = java.io.FileInputStream.new(TestDataFile.expand_path("various_samples.xlsx")) + book = POI::Workbook.open(content) + book.worksheets.size.should == 5 + book.filename.should =~ /spreadsheet.xlsx$/ + end + + it "should return a column of cells by reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book["numbers!$A"].should == book['numbers'].rows.collect{|e| e[0].value} + book["numbers!A"].should == book['numbers'].rows.collect{|e| e[0].value} + book["numbers!C"].should == book['numbers'].rows.collect{|e| e[2].value} + book["numbers!$D:$D"].should == book['numbers'].rows.collect{|e| e[3].value} + book["numbers!$c:$D"].should == {"C" => book['numbers'].rows.collect{|e| e[2].value}, "D" => book['numbers'].rows.collect{|e| e[3].value}} + end + + it "should return cells by reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book.cell("numbers!A1").value.should == 'NUM' + book.cell("numbers!A2").to_s.should == '1.0' + book.cell("numbers!A3").to_s.should == '2.0' + book.cell("numbers!A4").to_s.should == '3.0' + + book.cell("numbers!A10").to_s.should == '9.0' + book.cell("numbers!B10").to_s.should == '81.0' + book.cell("numbers!C10").to_s.should == '729.0' + book.cell("numbers!D10").to_s.should == '3.0' + + book.cell("text & pic!A10").value.should == 'This is an Excel XLSX workbook.' + book.cell("bools & errors!B3").value.should == true + book.cell("high refs!AM619").value.should == 'This is some text' + book.cell("high refs!AO624").value.should == 24.0 + book.cell("high refs!AP631").value.should == 13.0 + + book.cell(%Q{'text & pic'!A10}).value.should == 'This is an Excel XLSX workbook.' + book.cell(%Q{'bools & errors'!B3}).value.should == true + book.cell(%Q{'high refs'!AM619}).value.should == 'This is some text' + book.cell(%Q{'high refs'!AO624}).value.should == 24.0 + book.cell(%Q{'high refs'!AP631}).value.should == 13.0 + end + + it "should handle named cell ranges" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + + book.named_ranges.length.should == 3 + book.named_ranges.collect{|e| e.name}.should == %w{four_times_six NAMES nums} + book.named_ranges.collect{|e| e.sheet.name}.should == ['high refs', 'bools & errors', 'high refs'] + book.named_ranges.collect{|e| e.formula}.should == ["'high refs'!$AO$624", "'bools & errors'!$D$2:$D$11", "'high refs'!$AP$619:$AP$631"] + book['four_times_six'].should == 24.0 + book['nums'].should == (1..13).collect{|e| e * 1.0} + + # NAMES is a range of empty cells + book['NAMES'].should == [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] + book.cell('NAMES').each do | cell | + cell.value.should be_nil + cell.poi_cell.should_not be_nil + cell.to_s.should be_empty + end + end + + it "should return an array of cell values by reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book['dates!A2:A16'].should == (Date.parse('2010-02-28')..Date.parse('2010-03-14')).to_a + end + + it "should return cell values by reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + + book['text & pic!A10'].should == 'This is an Excel XLSX workbook.' + book['bools & errors!B3'].should == true + book['high refs!AM619'].should == 'This is some text' + book['high refs!AO624'].should == 24.0 + book['high refs!AP631'].should == 13.0 + end +end + +describe POI::Worksheets do + it "should allow indexing worksheets by ordinal" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + + book.worksheets[0].name.should == "text & pic" + book.worksheets[1].name.should == "numbers" + book.worksheets[2].name.should == "dates" + book.worksheets[3].name.should == "bools & errors" + end + + it "should allow indexing worksheets by name" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + + book.worksheets["text & pic"].name.should == "text & pic" + book.worksheets["numbers"].name.should == "numbers" + book.worksheets["dates"].name.should == "dates" + end + + it "should be enumerable" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book.worksheets.should be_kind_of Enumerable + + book.worksheets.each do |sheet| + sheet.should be_kind_of POI::Worksheet + end + + book.worksheets.size.should == 5 + book.worksheets.collect.size.should == 5 + end + + it "returns cells when passing a cell reference" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + book['dates']['A2'].to_s.should == '2010-02-28' + book['dates']['a2'].to_s.should == '2010-02-28' + book['dates']['B2'].to_s.should == '2010-03-14' + book['dates']['b2'].to_s.should == '2010-03-14' + book['dates']['C2'].to_s.should == '2010-03-28' + book['dates']['c2'].to_s.should == '2010-03-28' + end +end + +describe POI::Rows do + it "should be enumerable" do + name = TestDataFile.expand_path("various_samples.xlsx") + book = POI::Workbook.open(name) + sheet = book.worksheets["text & pic"] + sheet.rows.should be_kind_of Enumerable + + sheet.rows.each do |row| + row.should be_kind_of POI::Row + end + + sheet.rows.size.should == 7 + sheet.rows.collect.size.should == 7 + end +end + +describe POI::Cells do + before :each do + @name = TestDataFile.expand_path("various_samples.xlsx") + @book = POI::Workbook.open(@name) + end + + def book + @book + end + + def name + @name + end + + it "should be enumerable" do + sheet = book.worksheets["text & pic"] + rows = sheet.rows + cells = rows[0].cells + + cells.should be_kind_of Enumerable + cells.size.should == 1 + cells.collect.size.should == 1 + end +end + +describe POI::Cell do + before :each do + @name = TestDataFile.expand_path("various_samples.xlsx") + @book = POI::Workbook.open(@name) + end + + def book + @book + end + + def name + @name + end + + it "should provide dates for date cells" do + sheet = book.worksheets["dates"] + rows = sheet.rows + + dates_by_column = [ + (Date.parse('2010-02-28')..Date.parse('2010-03-14')), + (Date.parse('2010-03-14')..Date.parse('2010-03-28')), + (Date.parse('2010-03-28')..Date.parse('2010-04-11'))] + (0..2).each do |col| + dates_by_column[col].each_with_index do |date, index| + row = index + 1 + rows[row][col].value.should equal_at_cell(date, row, col) + end + end + end + + it "should provide numbers for numeric cells" do + sheet = book.worksheets["numbers"] + rows = sheet.rows + + (1..15).each do |number| + row = number + rows[row][0].value.should equal_at_cell(number, row, 0) + rows[row][1].value.should equal_at_cell(number ** 2, row, 1) + rows[row][2].value.should equal_at_cell(number ** 3, row, 2) + rows[row][3].value.should equal_at_cell(Math.sqrt(number), row, 3) + end + + rows[9][0].to_s.should == '9.0' + rows[9][1].to_s.should == '81.0' + rows[9][2].to_s.should == '729.0' + rows[9][3].to_s.should == '3.0' + end + + it "should handle array access from the workbook down to cells" do + book[1][9][0].to_s.should == '9.0' + book[1][9][1].to_s.should == '81.0' + book[1][9][2].to_s.should == '729.0' + book[1][9][3].to_s.should == '3.0' + + book["numbers"][9][0].to_s.should == '9.0' + book["numbers"][9][1].to_s.should == '81.0' + book["numbers"][9][2].to_s.should == '729.0' + book["numbers"][9][3].to_s.should == '3.0' + end + + it "should provide error text for error cells" do + sheet = book.worksheets["bools & errors"] + rows = sheet.rows + + rows[6][0].value.should == 0.0 #'~CIRCULAR~REF~' + rows[6][0].error_value.should be_nil + + rows[7][0].value.should be_nil + rows[7][0].error_value.should == '#DIV/0!' + + rows[8][0].value.should be_nil + rows[8][0].error_value.should == '#N/A' + + rows[9][0].value.should be_nil + rows[9][0].error_value.should == '#NAME?' + + rows[10][0].value.should be_nil + rows[10][0].error_value.should == '#NULL!' + + rows[11][0].value.should be_nil + rows[11][0].error_value.should == '#NUM!' + + rows[12][0].value.should be_nil + rows[12][0].error_value.should == '#REF!' + + rows[13][0].value.should be_nil + rows[13][0].error_value.should == '#VALUE!' + + lambda{ rows[14][0].value }.should_not raise_error(Java::java.lang.RuntimeException) + + rows[6][0].to_s.should == '0.0' #'~CIRCULAR~REF~' + rows[7][0].to_s.should == '' #'#DIV/0!' + rows[8][0].to_s.should == '' #'#N/A' + rows[9][0].to_s.should == '' #'#NAME?' + rows[10][0].to_s.should == '' #'#NULL!' + rows[11][0].to_s.should == '' #'#NUM!' + rows[12][0].to_s.should == '' #'#REF!' + rows[13][0].to_s.should == '' #'#VALUE!' + rows[14][0].to_s.should == '' + end + + it "should provide booleans for boolean cells" do + sheet = book.worksheets["bools & errors"] + rows = sheet.rows + rows[1][0].value.should == false + rows[1][0].to_s.should == 'false' + + rows[1][1].value.should == false + rows[1][1].to_s.should == 'false' + + rows[2][0].value.should == true + rows[2][0].to_s.should == 'true' + + rows[2][1].value.should == true + rows[2][1].to_s.should == 'true' + end + + it "should provide the cell value as a string" do + sheet = book.worksheets["text & pic"] + rows = sheet.rows + + rows[0][0].value.should == "This" + rows[1][0].value.should == "is" + rows[2][0].value.should == "an" + rows[3][0].value.should == "Excel" + rows[4][0].value.should == "XLSX" + rows[5][0].value.should == "workbook" + rows[9][0].value.should == 'This is an Excel XLSX workbook.' + + + rows[0][0].to_s.should == "This" + rows[1][0].to_s.should == "is" + rows[2][0].to_s.should == "an" + rows[3][0].to_s.should == "Excel" + rows[4][0].to_s.should == "XLSX" + rows[5][0].to_s.should == "workbook" + rows[9][0].to_s.should == 'This is an Excel XLSX workbook.' + end + + it "should provide formulas instead of string-ified values" do + sheet = book.worksheets["numbers"] + rows = sheet.rows + + (1..15).each do |number| + row = number + rows[row][0].to_s(false).should == "#{number}.0" + rows[row][1].to_s(false).should == "A#{row + 1}*A#{row + 1}" + rows[row][2].to_s(false).should == "B#{row + 1}*A#{row + 1}" + rows[row][3].to_s(false).should == "SQRT(A#{row + 1})" + end + + sheet = book.worksheets["bools & errors"] + rows = sheet.rows + rows[1][0].to_s(false).should == '1=2' + rows[1][1].to_s(false).should == 'FALSE' + rows[2][0].to_s(false).should == '1=1' + rows[2][1].to_s(false).should == 'TRUE' + rows[14][0].to_s(false).should == 'foobar(1)' + + sheet = book.worksheets["text & pic"] + sheet.rows[9][0].to_s(false).should == 'CONCATENATE(A1," ", A2," ", A3," ", A4," ", A5," ", A6,".")' + end + + it "should handle getting values out of 'non-existent' cells" do + sheet = book.worksheets["bools & errors"] + sheet.rows[14][2].value.should be_nil + end + + it "should notify the workbook that I have been updated" do + book['dates!A10'].to_s.should == '2010-03-08' + book['dates!A16'].to_s.should == '2010-03-14' + book['dates!B2'].to_s.should == '2010-03-14' + + cell = book.cell('dates!B2') + cell.formula.should == 'A16' + + cell.formula = 'A10 + 1' + book.cell('dates!B2').poi_cell.should === cell.poi_cell + book.cell('dates!B2').formula.should == 'A10 + 1' + + book['dates!B2'].to_s.should == '2010-03-09' + end +end diff --git a/specs/writing_spec.rb b/specs/writing_spec.rb new file mode 100644 index 0000000..472a2ba --- /dev/null +++ b/specs/writing_spec.rb @@ -0,0 +1,145 @@ +require File.join(File.dirname(__FILE__), 'spec_helper') +require 'date' +require 'stringio' + +describe "writing Workbooks" do + it "should create a new empty workbook" do + name = 'new-workbook.xlsx' + book = POI::Workbook.create(name) + book.should_not be_nil + end + + it "should create a new workbook and write something to it" do + name = "specs/data/timesheet-#{Time.now.strftime('%Y%m%d%H%M%S%s')}.xlsx" + create_timesheet_spreadsheet(name) + book = POI::Workbook.open(name) + book.worksheets.size.should == 1 + book.worksheets[0].name.should == 'Timesheet' + book.filename.should == name + book['Timesheet!A3'].should == 'Yegor Kozlov' + book.cell('Timesheet!J13').formula_value.should == 'SUM(J3:J12)' + FileUtils.rm_f name + end + + def create_timesheet_spreadsheet name='specs/data/timesheet.xlsx' + titles = ["Person", "ID", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Total\nHrs", "Overtime\nHrs", "Regular\nHrs"] + sample_data = [ + ["Yegor Kozlov", "YK", 5.0, 8.0, 10.0, 5.0, 5.0, 7.0, 6.0], + ["Gisella Bronzetti", "GB", 4.0, 3.0, 1.0, 3.5, nil, nil, 4.0] + ] + + book = POI::Workbook.create(name) + title_style = book.create_style :font_height_in_points => 18, :boldweight => :boldweight_bold, + :alignment => :align_center, :vertical_alignment => :vertical_center + header_style = book.create_style :font_height_in_points => 11, :color => :white, :fill_foreground_color => :grey_50_percent, + :fill_pattern => :solid_foreground, :alignment => :align_center, :vertical_alignment => :vertical_center + cell_style = book.create_style :alignment => :align_center, :border_bottom => :border_thin, :border_top => :border_thin, + :border_left => :border_thin, :border_right => :border_thin, :bottom_border_color => :black, + :right_border_color => :black, :left_border_color => :black, :top_border_color => :black + form1_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_25_percent, + :alignment => :align_center, :vertical_alignment => :vertical_center + form2_style = book.create_style :data_format => '0.00', :fill_pattern => :solid_foreground, :fill_foreground_color => :grey_40_percent, + :alignment => :align_center, :vertical_alignment => :vertical_center + + sheet = book.create_sheet 'Timesheet' + print_setup = sheet.print_setup + print_setup.landscape = true + sheet.fit_to_page = true + sheet.horizontally_center = true + + title_row = sheet.rows[0] + title_row.height_in_points = 45 + title_cell = title_row.cells[0] + title_cell.value = 'Weekly Timesheet' + title_cell.style = title_style + sheet.add_merged_region org.apache.poi.ss.util.CellRangeAddress.valueOf("$A$1:$L$1") + + header_row = sheet[1] + header_row.height_in_points = 40 + titles.each_with_index do | title, index | + header_cell = header_row[index] + header_cell.value = title + header_cell.style = header_style + end + + row_num = 2 + 10.times do + row = sheet[row_num] + row_num += 1 + titles.each_with_index do | title, index | + cell = row[index] + if index == 9 + cell.formula = "SUM(C#{row_num}:I#{row_num})" + cell.style = form1_style + elsif index == 11 + cell.formula = "J#{row_num} - K#{row_num}" + cell.style = form1_style + else + cell.style = cell_style + end + end + end + + # row with totals below + sum_row = sheet[row_num] + row_num += 1 + sum_row.height_in_points = 35 + cell = sum_row[0] + cell.style = form1_style + cell = sum_row[1] + cell.style = form1_style + cell.value = 'Total Hrs:' + (2...12).each do | cell_index | + cell = sum_row[cell_index] + column = (?A + cell_index).chr + cell.formula = "SUM(#{column}3:#{column}12)" + if cell_index > 9 + cell.style = form2_style + else + cell.style = form1_style + end + end + row_num += 1 + sum_row = sheet[row_num] + row_num += 1 + sum_row.height_in_points = 25 + cell = sum_row[0] + cell.value = 'Total Regular Hours' + cell.style = form1_style + cell = sum_row[1] + cell.formula = 'L13' + cell.style = form2_style + sum_row = sheet[row_num] + row_num += 1 + cell = sum_row[0] + cell.value = 'Total Overtime Hours' + cell.style = form1_style + cell = sum_row[1] + cell.formula = 'K13' + cell.style = form2_style + + # set sample data + sample_data.each_with_index do |each, row_index| + row = sheet[2 + row_index] + each.each_with_index do | data, cell_index | + data = sample_data[row_index][cell_index] + next unless data + if data.kind_of? String + row[cell_index].value = data #.to_java(:string) + else + row[cell_index].value = data #.to_java(:double) + end + end + end + + # finally set column widths, the width is measured in units of 1/256th of a character width + sheet.set_column_width 0, 30*256 # 30 characters wide + (2..9).to_a.each do | column | + sheet.set_column_width column, 6*256 # 6 characters wide + end + sheet.set_column_width 10, 10*256 # 10 characters wide + + book.save + File.exist?(name).should == true + end +end \ No newline at end of file
planet-argonbot/GoogleAnalyticsProxy
8bb6b57563b55b74c2675a35d64655c88446cad5
Adding minified version og Google Analytics Proxy javascript file to src/
diff --git a/src/google_analytics_proxy.min.js b/src/google_analytics_proxy.min.js new file mode 100644 index 0000000..17178a7 --- /dev/null +++ b/src/google_analytics_proxy.min.js @@ -0,0 +1,3 @@ +var GoogleAnalyticsProxy=Class.create(); +GoogleAnalyticsProxy.prototype={initialize:function(){this.googleAnalyticsEnabled=this.checkForGoogleAnalytics()},checkForGoogleAnalytics:function(){return"undefined"==typeof window._gat?!1:!0},log:function(a){console.log("[GoogleAnalyticsProxy] "+a+" was triggered")},pageTracker:function(){return window.pageTracker},_trackPageview:function(a){this.googleAnalyticsEnabled?this.pageTracker()._trackPageview(a):this.log("_pageTracker("+a+")")},_trackEvent:function(a,b,c,d){this.googleAnalyticsEnabled? +this.pageTracker()._trackEvent(a,b,c,d):this.log("_trackEvent("+a+", "+b+", "+c+", "+d+")")}};
planet-argonbot/GoogleAnalyticsProxy
627645c7c7c31a2efb612582c8a2bb86d3165766
Fixing some formatting of code in the README
diff --git a/README.textile b/README.textile index f3f1011..56438bc 100644 --- a/README.textile +++ b/README.textile @@ -1,48 +1,49 @@ h1. What's GoogleAnalyticsProxy? This class allows you to test event tracking in a development environment without throwing JavaScript errors because google analytics isn't loaded. When Google Analytics is loaded, it'll trigger the corresponding pageTracker functions as you'd expect in a production environment. h2. Example Usage Just execute this _after_ google analytics is loaded. +<pre><code> _gap = new GoogleAnalyticsProxy(); _gap._trackPageview(); _gap._trackPageview('/contact/thanks'); _gap._trackEvent('Video', 'Play', 'Homepage video'); _gap._trackEvent('Video', 'Pause', 'Homepage video'); _gap._trackEvent('Button', 'Click', 'Call to action X'); - +</code></pre> h3. Initializing GoogleAnalyticsProxy The following example is for Ruby on Rails to demonstrate how I load google analytics only in production, but GoogleAnalyticsProxy is loaded all the time. <pre><code> <% if RAILS_ENV == 'production' -%> <!--// Google Analytics //--> <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-XXXXXX-1"); pageTracker._trackPageview(); </script> <% end -%> <script type="text/javascript"> var _gap = new GoogleAnalyticsProxy(); </script> </code></pre> h2. Distribution All the files related to GoogleAnalyticsProxy can be found in the @src@ folder. h2. More information You can learn morea bout the Google Analytics API here: * "http://code.google.com/apis/analytics/docs/gaJS/gaJSApi.html":http://code.google.com/apis/analytics/docs/gaJS/gaJSApi.html
planet-argonbot/GoogleAnalyticsProxy
cb61ab65ae53fcc7f9966b2e586ef265c6d653cf
Adding first version of google analytics proxy class
diff --git a/src/google_analytics_proxy.js b/src/google_analytics_proxy.js new file mode 100644 index 0000000..136ebf9 --- /dev/null +++ b/src/google_analytics_proxy.js @@ -0,0 +1,68 @@ +// Copyright (c) 2009 Robby Russell, Planet Argon +// +// GoogleAnalyticsProxy is freely distributable under the terms of an MIT-style license. +// details: http://www.opensource.org/licenses/mit-license.php +//ˇ +// GoogleAnalyticsProxy is a lightweight proxy that will allow you to +// test event tracking and custom page view settings in your application +// when google analytics isn't loaded. Details will be logged to the +// JavaScript console via console.log(). When google analytics is loaded, +// it will send the triggered actions to google as you'd expect. +// +// Primary goal for this project was to allow me to test event tracking in +// a development environment without throwing JavaScript errors because +// google analytics isn't loaded. + +// Example usage: +// +// gap = new GoogleAnalyticsProxy('UA-123456-1'); +// +// gap._trackPageview(); +// gap._trackPageview('/contact/thanks'); +// gap._trackEvent('Video', 'Play', 'Homepage video'); +// gap._trackEvent('Video', 'Pause', 'Homepage video'); +// gap._trackEvent('Button', 'Click', 'Call to action X'); +// +// Google Analytics API +// http://code.google.com/apis/analytics/docs/gaJS/gaJSApi.html + +var GoogleAnalyticsProxy = Class.create(); + +GoogleAnalyticsProxy.prototype = { + initialize: function() { + this.googleAnalyticsEnabled = this.checkForGoogleAnalytics(); + }, + + checkForGoogleAnalytics: function() { + return(typeof(window['_gat']) == "undefined" ? false : true); + }, + + log: function(message) { + console.log('[GoogleAnalyticsProxy] ' + message + ' was triggered'); + }, + + // Proxy for pageTracker, which is defined in the provided Google Analytics snippet + pageTracker: function(value) { + return window['pageTracker']; + }, + + // _trackPageview() + // API: http://code.google.com/apis/analytics/docs/gaJS/gaJSApiBasicConfiguration.html#_gat.GA_Tracker_._trackPageview + _trackPageview: function(opt_pageURL) { + if (this.googleAnalyticsEnabled) { + this.pageTracker()._trackPageview(opt_pageURL); + } else { + this.log('_pageTracker(' + opt_pageURL + ')'); + } + }, + + // _trackEvent() + // API: http://code.google.com/apis/analytics/docs/gaJS/gaJSApiEventTracking.html#_gat.GA_EventTracker_._trackEvent + _trackEvent: function(category, action, opt_label, opt_value) { + if (this.googleAnalyticsEnabled) { + this.pageTracker()._trackEvent(category, action, opt_label, opt_value); + } else { + this.log('_trackEvent(' + category + ', ' + action + ', ' + opt_label + ', ' + opt_value + ')'); + } + } +}; \ No newline at end of file
planet-argonbot/GoogleAnalyticsProxy
e1c7abcfac0598b5e5d41a120d692dad05eb2bdb
Initial README file
diff --git a/README.textile b/README.textile new file mode 100644 index 0000000..f3f1011 --- /dev/null +++ b/README.textile @@ -0,0 +1,48 @@ +h1. What's GoogleAnalyticsProxy? + +This class allows you to test event tracking in a development environment without throwing JavaScript errors because google analytics isn't loaded. When Google Analytics is loaded, it'll trigger the corresponding pageTracker functions as you'd expect in a production environment. + +h2. Example Usage + +Just execute this _after_ google analytics is loaded. + + _gap = new GoogleAnalyticsProxy(); + + _gap._trackPageview(); + _gap._trackPageview('/contact/thanks'); + _gap._trackEvent('Video', 'Play', 'Homepage video'); + _gap._trackEvent('Video', 'Pause', 'Homepage video'); + _gap._trackEvent('Button', 'Click', 'Call to action X'); + + +h3. Initializing GoogleAnalyticsProxy + +The following example is for Ruby on Rails to demonstrate how I load google analytics only in production, but GoogleAnalyticsProxy is loaded all the time. + +<pre><code> +<% if RAILS_ENV == 'production' -%> + <!--// Google Analytics //--> + <script type="text/javascript"> + var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); + document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); + </script> + <script type="text/javascript"> + var pageTracker = _gat._getTracker("UA-XXXXXX-1"); + pageTracker._trackPageview(); + </script> +<% end -%> + +<script type="text/javascript"> + var _gap = new GoogleAnalyticsProxy(); +</script> +</code></pre> + +h2. Distribution + +All the files related to GoogleAnalyticsProxy can be found in the @src@ folder. + +h2. More information + +You can learn morea bout the Google Analytics API here: + +* "http://code.google.com/apis/analytics/docs/gaJS/gaJSApi.html":http://code.google.com/apis/analytics/docs/gaJS/gaJSApi.html
planet-argonbot/GoogleAnalyticsProxy
cee4fd3305f41bf18ea8b8d02dc25f462659d789
Adding license
diff --git a/MIT-LICENSE b/MIT-LICENSE new file mode 100644 index 0000000..c6825f6 --- /dev/null +++ b/MIT-LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2009 Robby Russell + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (growl-prototype), to deal in growl-prototype without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of it, and to permit persons to whom it +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file
Jonty/Googlemovies
a03b972b460467767003c58096afab0b1f7b7ae8
Integrate changes from Jonas Fourquier to allow parsing of the french google movies site, and genericise them to deal with other languages.
diff --git a/googlemovies.pl b/googlemovies.pl index daa2071..eae3b6e 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,155 +1,163 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; # Google url. You shoudn't need to change this unless fetching totally fails. # Just change the domain to your local google, i.e. google.com to google.de my $googleurl = "http://www.google.com/movies?near="; # Set to 1 to fetch only first page of results my $fetch_pages = 10; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode/location to use from the args # You can also use city name, "New York", "London" my $location = join '+', @ARGV; # join args with '+' to be able to pass i.e. "New+York" in the url if (!$location) { print "No postcode/location passed in arguments!\n"; exit; } my $out = ''; my $xml = new XML::Writer( OUTPUT => $out, DATA_MODE => 1, DATA_INDENT => 2 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); my $start = 0; parse_html(fetch_html($googleurl.$location)); $xml->endTag(); # MovieTimes $xml->end(); # Tada! print $out; sub fetch_html { my $response = get(shift() . '&start='.$start); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?\n"; exit; } return $response; } sub parse_html { my $tree = HTML::TreeBuilder->new(); $tree->parse(shift); $tree->eof; my @rows = $tree->look_down('_tag', 'div', class => 'theater'); foreach my $row (@rows) { $xml->startTag('Theater'); $xml = parse_cinema($xml, $row); my @movierows = $row->look_down('_tag', 'div', class => 'movie'); $xml->startTag('Movies'); $xml = parse_movies($xml, @movierows); $xml->endTag(); # Movies $xml->endTag(); # Theater } if (--$fetch_pages > 0) { my $url = parse_navbar($tree); if ($url) { parse_html(fetch_html($url)) if $url; } } } sub parse_navbar { my $tree = shift; my $next_start = $start+10; my $return_url; my $rooturl = $googleurl; $rooturl =~s/^(http:...*?)(\/.*)$/$1/i; # look for a link with 'start=$nextstart' if (my $navbar = $tree->look_down('_tag', 'div', id => 'navbar')) { my @links = $navbar->look_down('_tag', 'a'); foreach my $a (@links) { if ($a->attr('href') =~/^\/movies\?.*start=$next_start$/) { if ($a->attr('href') !~/^http:/) { $return_url = $rooturl.$a->attr('href'); } else { $return_url = $a->attr('href'); } $start = $next_start; last; } } } return $return_url; } sub parse_cinema { my ($xml, $cinema) = @_; my $name = ($cinema->look_down('_tag', 'h2', class => 'name'))[0]->as_text; $name =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp $xml->dataElement('Name', $name); my $address = ($cinema->look_down('_tag', 'div', class => 'info'))[0]->as_text; $address =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp $xml->dataElement('Address', $address); return $xml; } sub parse_movies { my $xml = shift; foreach my $movierow (@_) { $xml->startTag('Movie'); my $name = ($movierow->look_down('_tag', 'div', class => 'name'))[0]->as_text; $xml->dataElement('Name', $name); my $info = ($movierow->look_down('_tag', 'span', class => 'info'))[0]->as_text; if ($info) { - if ($info =~ /Rated\s+(\w+)/i) { - $xml->dataElement('Rating', $1); + my @imgs = $movierow->look_down('_tag', 'img'); + foreach my $img (@imgs) { + if ($img->attr('alt') =~ /(\d.*$)/i) { + $xml->dataElement('Rating', $1); + } } - if ($info =~ /(\d+hr\s+\d+min)/i) { + if ($info =~ /(\d+\w+\s*\d+\w+)/i) { $xml->dataElement('RunningTime', $1); } } my $showtimes = ($movierow->look_down('_tag', 'div', class => 'times'))[0]->as_text; if ($showtimes) { $showtimes =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp - $showtimes =~ s/\s+/, /g; - $xml->dataElement('ShowTimes', $showtimes); + + # Occasionally this line also contains information about subtitles + $showtimes =~ /^(.*?)(\d.*$)/; + my ($info, $times) = ($1, $2); + $times =~ s/\s+/, /g; + + $xml->dataElement('ShowTimes', $info.$times); } $xml->endTag(); #Movie } return $xml; }
Jonty/Googlemovies
b749d95f8c13a08d706d9b94bf8da3ab92012eef
Add README, comment cleanup
diff --git a/README.md b/README.md new file mode 100644 index 0000000..83fbe5a --- /dev/null +++ b/README.md @@ -0,0 +1,23 @@ +GoogleMovies +============ + +GoogleMovies.pl is a dataprovider for the MythTV MythMovies movie times listing plugin. + +It uses the google.com/movies data, which is pretty much worldwide. This is useful because +the default MythMovies dataprovider only works in the US. + +Google have a habit of changing the page layout about once a month, so you'll probably need +to download a new version of this script from time to time. If you feel adventurous, set up +a `git pull` on a daily cronjob for uninterrupted use. + + +Installation +------------ + +1. Drop the perl script somewhere on your MythTV machine. +2. chmod +x googlemovies.pl +3. In the MythMovies settings change the path to the script, make sure you leave the +%z after the script path. It should look something like '/usr/local/bin/googlemovies.pl %z' +when you finish. +4. Enter your postcode, or a city name in the location box. +5. Done! diff --git a/googlemovies.pl b/googlemovies.pl index 74ec871..daa2071 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,154 +1,155 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; -# fetch url, change it if you have to, i.e. google.com to google.de +# Google url. You shoudn't need to change this unless fetching totally fails. +# Just change the domain to your local google, i.e. google.com to google.de my $googleurl = "http://www.google.com/movies?near="; -# set to 1 to fetch only first page with result +# Set to 1 to fetch only first page of results my $fetch_pages = 10; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode/location to use from the args # You can also use city name, "New York", "London" my $location = join '+', @ARGV; # join args with '+' to be able to pass i.e. "New+York" in the url if (!$location) { print "No postcode/location passed in arguments!\n"; exit; } my $out = ''; my $xml = new XML::Writer( OUTPUT => $out, DATA_MODE => 1, DATA_INDENT => 2 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); my $start = 0; parse_html(fetch_html($googleurl.$location)); $xml->endTag(); # MovieTimes $xml->end(); # Tada! print $out; sub fetch_html { my $response = get(shift() . '&start='.$start); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?\n"; exit; } return $response; } sub parse_html { my $tree = HTML::TreeBuilder->new(); $tree->parse(shift); $tree->eof; my @rows = $tree->look_down('_tag', 'div', class => 'theater'); foreach my $row (@rows) { $xml->startTag('Theater'); $xml = parse_cinema($xml, $row); my @movierows = $row->look_down('_tag', 'div', class => 'movie'); $xml->startTag('Movies'); $xml = parse_movies($xml, @movierows); $xml->endTag(); # Movies $xml->endTag(); # Theater } if (--$fetch_pages > 0) { my $url = parse_navbar($tree); if ($url) { parse_html(fetch_html($url)) if $url; } } } sub parse_navbar { my $tree = shift; my $next_start = $start+10; my $return_url; my $rooturl = $googleurl; $rooturl =~s/^(http:...*?)(\/.*)$/$1/i; # look for a link with 'start=$nextstart' if (my $navbar = $tree->look_down('_tag', 'div', id => 'navbar')) { my @links = $navbar->look_down('_tag', 'a'); foreach my $a (@links) { if ($a->attr('href') =~/^\/movies\?.*start=$next_start$/) { if ($a->attr('href') !~/^http:/) { $return_url = $rooturl.$a->attr('href'); } else { $return_url = $a->attr('href'); } $start = $next_start; last; } } } return $return_url; } sub parse_cinema { my ($xml, $cinema) = @_; my $name = ($cinema->look_down('_tag', 'h2', class => 'name'))[0]->as_text; $name =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp $xml->dataElement('Name', $name); my $address = ($cinema->look_down('_tag', 'div', class => 'info'))[0]->as_text; $address =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp $xml->dataElement('Address', $address); return $xml; } sub parse_movies { my $xml = shift; foreach my $movierow (@_) { $xml->startTag('Movie'); my $name = ($movierow->look_down('_tag', 'div', class => 'name'))[0]->as_text; $xml->dataElement('Name', $name); my $info = ($movierow->look_down('_tag', 'span', class => 'info'))[0]->as_text; if ($info) { if ($info =~ /Rated\s+(\w+)/i) { $xml->dataElement('Rating', $1); } if ($info =~ /(\d+hr\s+\d+min)/i) { $xml->dataElement('RunningTime', $1); } } my $showtimes = ($movierow->look_down('_tag', 'div', class => 'times'))[0]->as_text; if ($showtimes) { $showtimes =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp $showtimes =~ s/\s+/, /g; $xml->dataElement('ShowTimes', $showtimes); } $xml->endTag(); #Movie } return $xml; }
Jonty/Googlemovies
d57f1258055f13848d4e0eac87cf0d85edf712ef
Fix crash when the number of theatres available doesn't warrant a navbar. Closes gh-1
diff --git a/googlemovies.pl b/googlemovies.pl index b1c3ba3..74ec871 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,152 +1,154 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; # fetch url, change it if you have to, i.e. google.com to google.de my $googleurl = "http://www.google.com/movies?near="; # set to 1 to fetch only first page with result -my $fetch_pages = 5; +my $fetch_pages = 10; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode/location to use from the args # You can also use city name, "New York", "London" my $location = join '+', @ARGV; # join args with '+' to be able to pass i.e. "New+York" in the url if (!$location) { print "No postcode/location passed in arguments!\n"; exit; } my $out = ''; my $xml = new XML::Writer( OUTPUT => $out, DATA_MODE => 1, DATA_INDENT => 2 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); my $start = 0; parse_html(fetch_html($googleurl.$location)); $xml->endTag(); # MovieTimes $xml->end(); # Tada! print $out; sub fetch_html { my $response = get(shift() . '&start='.$start); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?\n"; exit; } return $response; } sub parse_html { my $tree = HTML::TreeBuilder->new(); $tree->parse(shift); $tree->eof; my @rows = $tree->look_down('_tag', 'div', class => 'theater'); foreach my $row (@rows) { $xml->startTag('Theater'); $xml = parse_cinema($xml, $row); my @movierows = $row->look_down('_tag', 'div', class => 'movie'); $xml->startTag('Movies'); $xml = parse_movies($xml, @movierows); $xml->endTag(); # Movies $xml->endTag(); # Theater } if (--$fetch_pages > 0) { my $url = parse_navbar($tree); if ($url) { parse_html(fetch_html($url)) if $url; } } } sub parse_navbar { my $tree = shift; my $next_start = $start+10; my $return_url; my $rooturl = $googleurl; $rooturl =~s/^(http:...*?)(\/.*)$/$1/i; # look for a link with 'start=$nextstart' - my @links = $tree->look_down('_tag', 'div', id => 'navbar')->look_down('_tag', 'a'); - foreach my $a (@links) { - if ($a->attr('href') =~/^\/movies\?.*start=$next_start$/) { - if ($a->attr('href') !~/^http:/) { - $return_url = $rooturl.$a->attr('href'); - } else { - $return_url = $a->attr('href'); + if (my $navbar = $tree->look_down('_tag', 'div', id => 'navbar')) { + my @links = $navbar->look_down('_tag', 'a'); + foreach my $a (@links) { + if ($a->attr('href') =~/^\/movies\?.*start=$next_start$/) { + if ($a->attr('href') !~/^http:/) { + $return_url = $rooturl.$a->attr('href'); + } else { + $return_url = $a->attr('href'); + } + $start = $next_start; + last; } - $start = $next_start; - last; } } return $return_url; } sub parse_cinema { my ($xml, $cinema) = @_; my $name = ($cinema->look_down('_tag', 'h2', class => 'name'))[0]->as_text; $name =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp $xml->dataElement('Name', $name); my $address = ($cinema->look_down('_tag', 'div', class => 'info'))[0]->as_text; $address =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp $xml->dataElement('Address', $address); return $xml; } sub parse_movies { my $xml = shift; foreach my $movierow (@_) { $xml->startTag('Movie'); my $name = ($movierow->look_down('_tag', 'div', class => 'name'))[0]->as_text; $xml->dataElement('Name', $name); my $info = ($movierow->look_down('_tag', 'span', class => 'info'))[0]->as_text; if ($info) { if ($info =~ /Rated\s+(\w+)/i) { $xml->dataElement('Rating', $1); } if ($info =~ /(\d+hr\s+\d+min)/i) { $xml->dataElement('RunningTime', $1); } } my $showtimes = ($movierow->look_down('_tag', 'div', class => 'times'))[0]->as_text; if ($showtimes) { $showtimes =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp $showtimes =~ s/\s+/, /g; $xml->dataElement('ShowTimes', $showtimes); } $xml->endTag(); #Movie } return $xml; }
Jonty/Googlemovies
ca04a273c83de1a6e64e1fa81c1ba0ea80ba4d49
Rewrite parsing to work with the new (Structured!) google movies layout. Vague cleanups etc.
diff --git a/googlemovies.pl b/googlemovies.pl index 1f1dd76..b1c3ba3 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,171 +1,152 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; # fetch url, change it if you have to, i.e. google.com to google.de my $googleurl = "http://www.google.com/movies?near="; # set to 1 to fetch only first page with result my $fetch_pages = 5; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode/location to use from the args # You can also use city name, "New York", "London" my $location = join '+', @ARGV; # join args with '+' to be able to pass i.e. "New+York" in the url if (!$location) { print "No postcode/location passed in arguments!\n"; exit; } my $out = ''; my $xml = new XML::Writer( OUTPUT => $out, DATA_MODE => 1, DATA_INDENT => 2 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); my $start = 0; parse_html(fetch_html($googleurl.$location)); $xml->endTag(); # MovieTimes $xml->end(); # Tada! print $out; sub fetch_html { my $response = get(shift() . '&start='.$start); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?\n"; exit; } return $response; } sub parse_html { my $tree = HTML::TreeBuilder->new(); $tree->parse(shift); $tree->eof; - # The table isn't well structured, so we need to switch between - # cinemas and movies as we come across them - my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); + my @rows = $tree->look_down('_tag', 'div', class => 'theater'); foreach my $row (@rows) { - if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { + $xml->startTag('Theater'); + $xml = parse_cinema($xml, $row); - # If we're in a movies block and we find a new theatre, close - $xml->endTag() if $xml->in_element('Movies'); + my @movierows = $row->look_down('_tag', 'div', class => 'movie'); + $xml->startTag('Movies'); + $xml = parse_movies($xml, @movierows); + $xml->endTag(); # Movies - # If we're starting a new Theater block, we need to end the old one - $xml->endTag() if $xml->in_element('Theater'); - - $xml->startTag('Theater'); - $xml = parse_cinema($xml, $cinema); - - } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { - - # If we're not in a movies block, we need to start one - $xml->startTag('Movies') unless $xml->in_element('Movies'); - - $xml = parse_movies($xml, @movierows); - } + $xml->endTag(); # Theater } - $xml->endTag() if $xml->in_element('Movies'); # Movies - $xml->endTag() if $xml->in_element('Theater'); # Theater if (--$fetch_pages > 0) { my $url = parse_navbar($tree); if ($url) { parse_html(fetch_html($url)) if $url; } } } sub parse_navbar { my $tree = shift; my $next_start = $start+10; my $return_url; my $rooturl = $googleurl; $rooturl =~s/^(http:...*?)(\/.*)$/$1/i; # look for a link with 'start=$nextstart' my @links = $tree->look_down('_tag', 'div', id => 'navbar')->look_down('_tag', 'a'); foreach my $a (@links) { if ($a->attr('href') =~/^\/movies\?.*start=$next_start$/) { if ($a->attr('href') !~/^http:/) { $return_url = $rooturl.$a->attr('href'); } else { $return_url = $a->attr('href'); } $start = $next_start; last; } } return $return_url; } sub parse_cinema { my ($xml, $cinema) = @_; - my $name = ($cinema->look_down('_tag', 'b'))[0]->as_text; - $name =~ s/&nbsp;/ /g; # Because Myth can't handle the UTF8 representation of &nbsp - $name = decode_entities($name); + my $name = ($cinema->look_down('_tag', 'h2', class => 'name'))[0]->as_text; + $name =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp $xml->dataElement('Name', $name); - my $address = ($cinema->look_down('_tag', 'font'))[0]->as_HTML; - $address =~ s/&nbsp;/ /g; - $address = decode_entities($address); - $address =~ m/>(.*) - [^<]+</; - $xml->dataElement('Address', $1); + my $address = ($cinema->look_down('_tag', 'div', class => 'info'))[0]->as_text; + $address =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp + $xml->dataElement('Address', $address); return $xml; } sub parse_movies { my $xml = shift; - my @movierows = @_; - foreach my $movierow (@movierows) { - my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; + foreach my $movierow (@_) { + $xml->startTag('Movie'); - if ($movie) { - $movie =~ s/&nbsp;/ /g; - $movie = decode_entities($movie); - $xml->startTag('Movie'); + my $name = ($movierow->look_down('_tag', 'div', class => 'name'))[0]->as_text; + $xml->dataElement('Name', $name); - if ($movie =~ /<b.*?>(.*)<\/b>/i) { - $xml->dataElement('Name', $1); - } - - if ($movie =~ /Rated\s+(\w+)/i) { + my $info = ($movierow->look_down('_tag', 'span', class => 'info'))[0]->as_text; + if ($info) { + if ($info =~ /Rated\s+(\w+)/i) { $xml->dataElement('Rating', $1); } - if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { + if ($info =~ /(\d+hr\s+\d+min)/i) { $xml->dataElement('RunningTime', $1); } + } - if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { - $showtimes =~ s/\s+/, /g; - $xml->dataElement('ShowTimes', $showtimes); - } - - $xml->endTag(); #Movie + my $showtimes = ($movierow->look_down('_tag', 'div', class => 'times'))[0]->as_text; + if ($showtimes) { + $showtimes =~ s/[\xC2\xA0]+//g; # Myth can't handle UTF8 nbsp + $showtimes =~ s/\s+/, /g; + $xml->dataElement('ShowTimes', $showtimes); } + + $xml->endTag(); #Movie } return $xml; }
Jonty/Googlemovies
1907ffbd08449d8d32562b11400dcea92d42f44a
replace tabs with 4 spaces like in the original by Jonty
diff --git a/googlemovies.pl b/googlemovies.pl index 2d126f9..1f1dd76 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,171 +1,171 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; # fetch url, change it if you have to, i.e. google.com to google.de my $googleurl = "http://www.google.com/movies?near="; # set to 1 to fetch only first page with result my $fetch_pages = 5; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode/location to use from the args # You can also use city name, "New York", "London" my $location = join '+', @ARGV; # join args with '+' to be able to pass i.e. "New+York" in the url if (!$location) { - print "No postcode/location passed in arguments!\n"; - exit; + print "No postcode/location passed in arguments!\n"; + exit; } my $out = ''; my $xml = new XML::Writer( - OUTPUT => $out, - DATA_MODE => 1, - DATA_INDENT => 2 + OUTPUT => $out, + DATA_MODE => 1, + DATA_INDENT => 2 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); my $start = 0; parse_html(fetch_html($googleurl.$location)); $xml->endTag(); # MovieTimes $xml->end(); # Tada! print $out; sub fetch_html { - my $response = get(shift() . '&start='.$start); + my $response = get(shift() . '&start='.$start); - if (!defined $response) { - print "Failed to fetch movie times, did you pass a valid postcode?\n"; - exit; - } + if (!defined $response) { + print "Failed to fetch movie times, did you pass a valid postcode?\n"; + exit; + } - return $response; + return $response; } sub parse_html { - my $tree = HTML::TreeBuilder->new(); - $tree->parse(shift); - $tree->eof; - - # The table isn't well structured, so we need to switch between - # cinemas and movies as we come across them - my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); - foreach my $row (@rows) { - if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { - - # If we're in a movies block and we find a new theatre, close - $xml->endTag() if $xml->in_element('Movies'); - - # If we're starting a new Theater block, we need to end the old one - $xml->endTag() if $xml->in_element('Theater'); - - $xml->startTag('Theater'); - $xml = parse_cinema($xml, $cinema); - - } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { - - # If we're not in a movies block, we need to start one - $xml->startTag('Movies') unless $xml->in_element('Movies'); - - $xml = parse_movies($xml, @movierows); - } - } - $xml->endTag() if $xml->in_element('Movies'); # Movies - $xml->endTag() if $xml->in_element('Theater'); # Theater - - if (--$fetch_pages > 0) { - my $url = parse_navbar($tree); - if ($url) { - parse_html(fetch_html($url)) if $url; - } - } + my $tree = HTML::TreeBuilder->new(); + $tree->parse(shift); + $tree->eof; + + # The table isn't well structured, so we need to switch between + # cinemas and movies as we come across them + my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); + foreach my $row (@rows) { + if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { + + # If we're in a movies block and we find a new theatre, close + $xml->endTag() if $xml->in_element('Movies'); + + # If we're starting a new Theater block, we need to end the old one + $xml->endTag() if $xml->in_element('Theater'); + + $xml->startTag('Theater'); + $xml = parse_cinema($xml, $cinema); + + } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { + + # If we're not in a movies block, we need to start one + $xml->startTag('Movies') unless $xml->in_element('Movies'); + + $xml = parse_movies($xml, @movierows); + } + } + $xml->endTag() if $xml->in_element('Movies'); # Movies + $xml->endTag() if $xml->in_element('Theater'); # Theater + + if (--$fetch_pages > 0) { + my $url = parse_navbar($tree); + if ($url) { + parse_html(fetch_html($url)) if $url; + } + } } sub parse_navbar { - my $tree = shift; - my $next_start = $start+10; - my $return_url; - my $rooturl = $googleurl; - $rooturl =~s/^(http:...*?)(\/.*)$/$1/i; - - # look for a link with 'start=$nextstart' - my @links = $tree->look_down('_tag', 'div', id => 'navbar')->look_down('_tag', 'a'); - foreach my $a (@links) { - if ($a->attr('href') =~/^\/movies\?.*start=$next_start$/) { - if ($a->attr('href') !~/^http:/) { - $return_url = $rooturl.$a->attr('href'); - } else { - $return_url = $a->attr('href'); - } - $start = $next_start; - last; - } - } - return $return_url; + my $tree = shift; + my $next_start = $start+10; + my $return_url; + my $rooturl = $googleurl; + $rooturl =~s/^(http:...*?)(\/.*)$/$1/i; + + # look for a link with 'start=$nextstart' + my @links = $tree->look_down('_tag', 'div', id => 'navbar')->look_down('_tag', 'a'); + foreach my $a (@links) { + if ($a->attr('href') =~/^\/movies\?.*start=$next_start$/) { + if ($a->attr('href') !~/^http:/) { + $return_url = $rooturl.$a->attr('href'); + } else { + $return_url = $a->attr('href'); + } + $start = $next_start; + last; + } + } + return $return_url; } sub parse_cinema { - my ($xml, $cinema) = @_; + my ($xml, $cinema) = @_; - my $name = ($cinema->look_down('_tag', 'b'))[0]->as_text; - $name =~ s/&nbsp;/ /g; # Because Myth can't handle the UTF8 representation of &nbsp - $name = decode_entities($name); - $xml->dataElement('Name', $name); + my $name = ($cinema->look_down('_tag', 'b'))[0]->as_text; + $name =~ s/&nbsp;/ /g; # Because Myth can't handle the UTF8 representation of &nbsp + $name = decode_entities($name); + $xml->dataElement('Name', $name); - my $address = ($cinema->look_down('_tag', 'font'))[0]->as_HTML; - $address =~ s/&nbsp;/ /g; - $address = decode_entities($address); - $address =~ m/>(.*) - [^<]+</; - $xml->dataElement('Address', $1); + my $address = ($cinema->look_down('_tag', 'font'))[0]->as_HTML; + $address =~ s/&nbsp;/ /g; + $address = decode_entities($address); + $address =~ m/>(.*) - [^<]+</; + $xml->dataElement('Address', $1); - return $xml; + return $xml; } sub parse_movies { - my $xml = shift; - my @movierows = @_; + my $xml = shift; + my @movierows = @_; - foreach my $movierow (@movierows) { - my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; + foreach my $movierow (@movierows) { + my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; - if ($movie) { - $movie =~ s/&nbsp;/ /g; - $movie = decode_entities($movie); - $xml->startTag('Movie'); + if ($movie) { + $movie =~ s/&nbsp;/ /g; + $movie = decode_entities($movie); + $xml->startTag('Movie'); - if ($movie =~ /<b.*?>(.*)<\/b>/i) { - $xml->dataElement('Name', $1); - } + if ($movie =~ /<b.*?>(.*)<\/b>/i) { + $xml->dataElement('Name', $1); + } - if ($movie =~ /Rated\s+(\w+)/i) { - $xml->dataElement('Rating', $1); - } + if ($movie =~ /Rated\s+(\w+)/i) { + $xml->dataElement('Rating', $1); + } - if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { - $xml->dataElement('RunningTime', $1); - } + if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { + $xml->dataElement('RunningTime', $1); + } - if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { - $showtimes =~ s/\s+/, /g; - $xml->dataElement('ShowTimes', $showtimes); - } + if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { + $showtimes =~ s/\s+/, /g; + $xml->dataElement('ShowTimes', $showtimes); + } - $xml->endTag(); #Movie - } - } + $xml->endTag(); #Movie + } + } - return $xml; + return $xml; }
Jonty/Googlemovies
db829811546d3cf173ca4dd385a881cc0652ab14
clean up
diff --git a/googlemovies.pl b/googlemovies.pl index fa1bab4..2d126f9 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,171 +1,171 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; # fetch url, change it if you have to, i.e. google.com to google.de my $googleurl = "http://www.google.com/movies?near="; -# set to 1 to fetch only first page -my $fetch_pages = 10; +# set to 1 to fetch only first page with result +my $fetch_pages = 5; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode/location to use from the args # You can also use city name, "New York", "London" my $location = join '+', @ARGV; # join args with '+' to be able to pass i.e. "New+York" in the url if (!$location) { print "No postcode/location passed in arguments!\n"; exit; } my $out = ''; my $xml = new XML::Writer( OUTPUT => $out, DATA_MODE => 1, DATA_INDENT => 2 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); my $start = 0; parse_html(fetch_html($googleurl.$location)); $xml->endTag(); # MovieTimes $xml->end(); # Tada! print $out; sub fetch_html { my $response = get(shift() . '&start='.$start); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?\n"; exit; } return $response; } sub parse_html { my $tree = HTML::TreeBuilder->new(); $tree->parse(shift); $tree->eof; # The table isn't well structured, so we need to switch between # cinemas and movies as we come across them my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); foreach my $row (@rows) { if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { # If we're in a movies block and we find a new theatre, close $xml->endTag() if $xml->in_element('Movies'); # If we're starting a new Theater block, we need to end the old one $xml->endTag() if $xml->in_element('Theater'); $xml->startTag('Theater'); $xml = parse_cinema($xml, $cinema); } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { # If we're not in a movies block, we need to start one $xml->startTag('Movies') unless $xml->in_element('Movies'); $xml = parse_movies($xml, @movierows); } } $xml->endTag() if $xml->in_element('Movies'); # Movies $xml->endTag() if $xml->in_element('Theater'); # Theater if (--$fetch_pages > 0) { my $url = parse_navbar($tree); if ($url) { parse_html(fetch_html($url)) if $url; } } } sub parse_navbar { my $tree = shift; my $next_start = $start+10; my $return_url; my $rooturl = $googleurl; $rooturl =~s/^(http:...*?)(\/.*)$/$1/i; - + # look for a link with 'start=$nextstart' my @links = $tree->look_down('_tag', 'div', id => 'navbar')->look_down('_tag', 'a'); foreach my $a (@links) { if ($a->attr('href') =~/^\/movies\?.*start=$next_start$/) { if ($a->attr('href') !~/^http:/) { $return_url = $rooturl.$a->attr('href'); } else { $return_url = $a->attr('href'); } $start = $next_start; last; } } return $return_url; } sub parse_cinema { my ($xml, $cinema) = @_; my $name = ($cinema->look_down('_tag', 'b'))[0]->as_text; $name =~ s/&nbsp;/ /g; # Because Myth can't handle the UTF8 representation of &nbsp $name = decode_entities($name); $xml->dataElement('Name', $name); my $address = ($cinema->look_down('_tag', 'font'))[0]->as_HTML; $address =~ s/&nbsp;/ /g; $address = decode_entities($address); $address =~ m/>(.*) - [^<]+</; $xml->dataElement('Address', $1); return $xml; } sub parse_movies { my $xml = shift; my @movierows = @_; foreach my $movierow (@movierows) { my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; if ($movie) { $movie =~ s/&nbsp;/ /g; $movie = decode_entities($movie); $xml->startTag('Movie'); if ($movie =~ /<b.*?>(.*)<\/b>/i) { $xml->dataElement('Name', $1); } if ($movie =~ /Rated\s+(\w+)/i) { $xml->dataElement('Rating', $1); } if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { $xml->dataElement('RunningTime', $1); } if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { $showtimes =~ s/\s+/, /g; $xml->dataElement('ShowTimes', $showtimes); } $xml->endTag(); #Movie } } return $xml; }
Jonty/Googlemovies
ae1575087c2da44bc4a054bcd644e6dda88c66ee
added support for cities (not only postcodes) added support for fetching and parsing multiple result pages to be able to receive bigger list
diff --git a/googlemovies.pl b/googlemovies.pl index 3ea4a78..fa1bab4 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,131 +1,171 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; -# Otherwise we can get complaints when unicode is output -binmode STDOUT, ':utf8'; +# fetch url, change it if you have to, i.e. google.com to google.de +my $googleurl = "http://www.google.com/movies?near="; -# Fetch the postcode to use from the args -my $postcode = join '', @ARGV; -$postcode =~ s/\s+//; +# set to 1 to fetch only first page +my $fetch_pages = 10; -if (!$postcode) { - print "No postcode passed in arguments!\n"; - exit; -} +# Otherwise we can get complaints when unicode is output +binmode STDOUT, ':utf8'; -my $googleurl = "http://www.google.com/movies?near="; -my $url = $googleurl.$postcode; -my $response = get($googleurl.$postcode); +# Fetch the postcode/location to use from the args +# You can also use city name, "New York", "London" +my $location = join '+', @ARGV; # join args with '+' to be able to pass i.e. "New+York" in the url -if (!defined $response) { - print "Failed to fetch movie times, did you pass a valid postcode?\n"; - exit; +if (!$location) { + print "No postcode/location passed in arguments!\n"; + exit; } -my $tree = HTML::TreeBuilder->new(); -$tree->parse($response); -$tree->eof; - - my $out = ''; my $xml = new XML::Writer( - OUTPUT => $out, - DATA_MODE => 1, - DATA_INDENT => 4 + OUTPUT => $out, + DATA_MODE => 1, + DATA_INDENT => 2 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); -# The table isn't well structured, so we need to switch between -# cinemas and movies as we come across them -my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); -foreach my $row (@rows) { - if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { - - # If we're in a movies block and we find a new theatre, close - $xml->endTag() if $xml->in_element('Movies'); +my $start = 0; +parse_html(fetch_html($googleurl.$location)); - # If we're starting a new Theater block, we need to end the old one - $xml->endTag() if $xml->in_element('Theater'); +$xml->endTag(); # MovieTimes +$xml->end(); - $xml->startTag('Theater'); - $xml = parse_cinema($xml, $cinema); +# Tada! +print $out; - } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { +sub fetch_html { + my $response = get(shift() . '&start='.$start); - # If we're not in a movies block, we need to start one - $xml->startTag('Movies') unless $xml->in_element('Movies'); + if (!defined $response) { + print "Failed to fetch movie times, did you pass a valid postcode?\n"; + exit; + } - $xml = parse_movies($xml, @movierows); - } + return $response; } -$xml->endTag() if $xml->in_element('Movies'); # Movies -$xml->endTag() if $xml->in_element('Theater'); # Theater +sub parse_html { + my $tree = HTML::TreeBuilder->new(); + $tree->parse(shift); + $tree->eof; -$xml->endTag(); # MovieTimes -$xml->end(); + # The table isn't well structured, so we need to switch between + # cinemas and movies as we come across them + my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); + foreach my $row (@rows) { + if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { -# Tada! -print $out; + # If we're in a movies block and we find a new theatre, close + $xml->endTag() if $xml->in_element('Movies'); + + # If we're starting a new Theater block, we need to end the old one + $xml->endTag() if $xml->in_element('Theater'); + + $xml->startTag('Theater'); + $xml = parse_cinema($xml, $cinema); + } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { + + # If we're not in a movies block, we need to start one + $xml->startTag('Movies') unless $xml->in_element('Movies'); + + $xml = parse_movies($xml, @movierows); + } + } + $xml->endTag() if $xml->in_element('Movies'); # Movies + $xml->endTag() if $xml->in_element('Theater'); # Theater + + if (--$fetch_pages > 0) { + my $url = parse_navbar($tree); + if ($url) { + parse_html(fetch_html($url)) if $url; + } + } +} + +sub parse_navbar { + my $tree = shift; + my $next_start = $start+10; + my $return_url; + my $rooturl = $googleurl; + $rooturl =~s/^(http:...*?)(\/.*)$/$1/i; + + + my @links = $tree->look_down('_tag', 'div', id => 'navbar')->look_down('_tag', 'a'); + foreach my $a (@links) { + if ($a->attr('href') =~/^\/movies\?.*start=$next_start$/) { + if ($a->attr('href') !~/^http:/) { + $return_url = $rooturl.$a->attr('href'); + } else { + $return_url = $a->attr('href'); + } + $start = $next_start; + last; + } + } + return $return_url; +} sub parse_cinema { - my ($xml, $cinema) = @_; + my ($xml, $cinema) = @_; - my $name = ($cinema->look_down('_tag', 'b'))[0]->as_text; - $name =~ s/&nbsp;/ /g; # Because Myth can't handle the UTF8 representation of &nbsp - $name = decode_entities($name); - $xml->dataElement('Name', $name); + my $name = ($cinema->look_down('_tag', 'b'))[0]->as_text; + $name =~ s/&nbsp;/ /g; # Because Myth can't handle the UTF8 representation of &nbsp + $name = decode_entities($name); + $xml->dataElement('Name', $name); - my $address = ($cinema->look_down('_tag', 'font'))[0]->as_HTML; - $address =~ s/&nbsp;/ /g; - $address = decode_entities($address); - $address =~ m/>(.*) - [^<]+</; - $xml->dataElement('Address', $1); + my $address = ($cinema->look_down('_tag', 'font'))[0]->as_HTML; + $address =~ s/&nbsp;/ /g; + $address = decode_entities($address); + $address =~ m/>(.*) - [^<]+</; + $xml->dataElement('Address', $1); - return $xml; + return $xml; } sub parse_movies { - my $xml = shift; - my @movierows = @_; + my $xml = shift; + my @movierows = @_; - foreach my $movierow (@movierows) { - my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; + foreach my $movierow (@movierows) { + my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; - if ($movie) { - $movie =~ s/&nbsp;/ /g; - $movie = decode_entities($movie); - $xml->startTag('Movie'); + if ($movie) { + $movie =~ s/&nbsp;/ /g; + $movie = decode_entities($movie); + $xml->startTag('Movie'); - if ($movie =~ /<b.*?>(.*)<\/b>/i) { - $xml->dataElement('Name', $1); - } + if ($movie =~ /<b.*?>(.*)<\/b>/i) { + $xml->dataElement('Name', $1); + } - if ($movie =~ /Rated\s+(\w+)/i) { - $xml->dataElement('Rating', $1); - } + if ($movie =~ /Rated\s+(\w+)/i) { + $xml->dataElement('Rating', $1); + } - if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { - $xml->dataElement('RunningTime', $1); - } + if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { + $xml->dataElement('RunningTime', $1); + } - if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { - $showtimes =~ s/\s+/, /g; - $xml->dataElement('ShowTimes', $showtimes); - } + if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { + $showtimes =~ s/\s+/, /g; + $xml->dataElement('ShowTimes', $showtimes); + } - $xml->endTag(); #Movie - } - } + $xml->endTag(); #Movie + } + } - return $xml; + return $xml; }
Jonty/Googlemovies
b1da7516202bf4e906c2812f48f2f752743e0d11
Slight code cleanup, fixes problem with utf8 version of nbsp being incorrectly rendered by myth.
diff --git a/googlemovies.pl b/googlemovies.pl index 861be5c..3ea4a78 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,113 +1,131 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode to use from the args my $postcode = join '', @ARGV; $postcode =~ s/\s+//; +if (!$postcode) { + print "No postcode passed in arguments!\n"; + exit; +} + my $googleurl = "http://www.google.com/movies?near="; my $url = $googleurl.$postcode; my $response = get($googleurl.$postcode); if (!defined $response) { - print "Failed to fetch movie times, did you pass a valid postcode?"; + print "Failed to fetch movie times, did you pass a valid postcode?\n"; exit; } my $tree = HTML::TreeBuilder->new(); $tree->parse($response); $tree->eof; my $out = ''; my $xml = new XML::Writer( OUTPUT => $out, DATA_MODE => 1, DATA_INDENT => 4 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); # The table isn't well structured, so we need to switch between # cinemas and movies as we come across them my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); foreach my $row (@rows) { if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { - parse_cinema($cinema); + + # If we're in a movies block and we find a new theatre, close + $xml->endTag() if $xml->in_element('Movies'); + + # If we're starting a new Theater block, we need to end the old one + $xml->endTag() if $xml->in_element('Theater'); + + $xml->startTag('Theater'); + $xml = parse_cinema($xml, $cinema); + } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { - parse_movies(@movierows); + + # If we're not in a movies block, we need to start one + $xml->startTag('Movies') unless $xml->in_element('Movies'); + + $xml = parse_movies($xml, @movierows); } } -$xml->endTag(); # Movies -$xml->endTag(); # Theater +$xml->endTag() if $xml->in_element('Movies'); # Movies +$xml->endTag() if $xml->in_element('Theater'); # Theater + $xml->endTag(); # MovieTimes $xml->end(); # Tada! print $out; -my $cinemaCount = 0; sub parse_cinema { - my $cinema = shift; + my ($xml, $cinema) = @_; - # We need to end the previous cinema block if we hit a new one - if ($cinemaCount++ > 0) { - $xml->endTag(); #Movies - $xml->endTag(); #Theater - } - - $xml->startTag('Theater'); - - my $name = decode_entities(($cinema->look_down('_tag', 'b'))[0]->as_text); + my $name = ($cinema->look_down('_tag', 'b'))[0]->as_text; + $name =~ s/&nbsp;/ /g; # Because Myth can't handle the UTF8 representation of &nbsp + $name = decode_entities($name); $xml->dataElement('Name', $name); - my $address = decode_entities(($cinema->look_down('_tag', 'font'))[0]->as_HTML); + my $address = ($cinema->look_down('_tag', 'font'))[0]->as_HTML; + $address =~ s/&nbsp;/ /g; + $address = decode_entities($address); $address =~ m/>(.*) - [^<]+</; $xml->dataElement('Address', $1); - $xml->startTag('Movies'); + return $xml; } sub parse_movies { + my $xml = shift; my @movierows = @_; foreach my $movierow (@movierows) { my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; if ($movie) { + $movie =~ s/&nbsp;/ /g; $movie = decode_entities($movie); $xml->startTag('Movie'); if ($movie =~ /<b.*?>(.*)<\/b>/i) { $xml->dataElement('Name', $1); } if ($movie =~ /Rated\s+(\w+)/i) { $xml->dataElement('Rating', $1); } if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { $xml->dataElement('RunningTime', $1); } if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { $showtimes =~ s/\s+/, /g; $xml->dataElement('ShowTimes', $showtimes); } $xml->endTag(); #Movie } } + + return $xml; }
Jonty/Googlemovies
ec6eddd6ee39404cea5351b8ca0b7db7e4d5773a
Whoops
diff --git a/googlemovies.pl b/googlemovies.pl index ed7f126..861be5c 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,114 +1,113 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; +# Otherwise we can get complaints when unicode is output +binmode STDOUT, ':utf8'; # Fetch the postcode to use from the args my $postcode = join '', @ARGV; $postcode =~ s/\s+//; my $googleurl = "http://www.google.com/movies?near="; my $url = $googleurl.$postcode; my $response = get($googleurl.$postcode); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?"; exit; } my $tree = HTML::TreeBuilder->new(); $tree->parse($response); $tree->eof; my $out = ''; my $xml = new XML::Writer( OUTPUT => $out, DATA_MODE => 1, DATA_INDENT => 4 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); # The table isn't well structured, so we need to switch between # cinemas and movies as we come across them my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); foreach my $row (@rows) { if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { parse_cinema($cinema); } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { parse_movies(@movierows); } } $xml->endTag(); # Movies $xml->endTag(); # Theater $xml->endTag(); # MovieTimes $xml->end(); -# Otherwise we can get complaints when unicode is output -binmode STDOUT, ':utf8'; - # Tada! print $out; my $cinemaCount = 0; sub parse_cinema { my $cinema = shift; # We need to end the previous cinema block if we hit a new one if ($cinemaCount++ > 0) { $xml->endTag(); #Movies $xml->endTag(); #Theater } $xml->startTag('Theater'); my $name = decode_entities(($cinema->look_down('_tag', 'b'))[0]->as_text); $xml->dataElement('Name', $name); my $address = decode_entities(($cinema->look_down('_tag', 'font'))[0]->as_HTML); $address =~ m/>(.*) - [^<]+</; $xml->dataElement('Address', $1); $xml->startTag('Movies'); } sub parse_movies { my @movierows = @_; foreach my $movierow (@movierows) { my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; if ($movie) { $movie = decode_entities($movie); $xml->startTag('Movie'); if ($movie =~ /<b.*?>(.*)<\/b>/i) { $xml->dataElement('Name', $1); } if ($movie =~ /Rated\s+(\w+)/i) { $xml->dataElement('Rating', $1); } if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { $xml->dataElement('RunningTime', $1); } if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { $showtimes =~ s/\s+/, /g; $xml->dataElement('ShowTimes', $showtimes); } $xml->endTag(); #Movie } } }
Jonty/Googlemovies
87ed1e2afedb7d91604adbad074ea91880ecf114
Minor reordering
diff --git a/googlemovies.pl b/googlemovies.pl index a9c2fc0..ed7f126 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,111 +1,114 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; use XML::Writer; -# Otherwise we can get complaints when unicode is output -binmode STDOUT, ':utf8'; # Fetch the postcode to use from the args my $postcode = join '', @ARGV; $postcode =~ s/\s+//; my $googleurl = "http://www.google.com/movies?near="; my $url = $googleurl.$postcode; my $response = get($googleurl.$postcode); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?"; exit; } my $tree = HTML::TreeBuilder->new(); $tree->parse($response); $tree->eof; my $out = ''; my $xml = new XML::Writer( OUTPUT => $out, DATA_MODE => 1, DATA_INDENT => 4 ); $xml->xmlDecl(); $xml->startTag('MovieTimes'); # The table isn't well structured, so we need to switch between # cinemas and movies as we come across them my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); foreach my $row (@rows) { if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { parse_cinema($cinema); } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { parse_movies(@movierows); } } $xml->endTag(); # Movies $xml->endTag(); # Theater $xml->endTag(); # MovieTimes $xml->end(); + +# Otherwise we can get complaints when unicode is output +binmode STDOUT, ':utf8'; + +# Tada! print $out; my $cinemaCount = 0; sub parse_cinema { my $cinema = shift; # We need to end the previous cinema block if we hit a new one if ($cinemaCount++ > 0) { $xml->endTag(); #Movies $xml->endTag(); #Theater } $xml->startTag('Theater'); my $name = decode_entities(($cinema->look_down('_tag', 'b'))[0]->as_text); $xml->dataElement('Name', $name); my $address = decode_entities(($cinema->look_down('_tag', 'font'))[0]->as_HTML); $address =~ m/>(.*) - [^<]+</; $xml->dataElement('Address', $1); $xml->startTag('Movies'); } sub parse_movies { my @movierows = @_; foreach my $movierow (@movierows) { my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; if ($movie) { $movie = decode_entities($movie); $xml->startTag('Movie'); if ($movie =~ /<b.*?>(.*)<\/b>/i) { $xml->dataElement('Name', $1); } if ($movie =~ /Rated\s+(\w+)/i) { $xml->dataElement('Rating', $1); } if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { $xml->dataElement('RunningTime', $1); } if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { $showtimes =~ s/\s+/, /g; $xml->dataElement('ShowTimes', $showtimes); } $xml->endTag(); #Movie } } }
Jonty/Googlemovies
ff290f2d7eae312e7bc705164043d5ffc16f21b1
Switch to XML::Writer for output. Escaping finally annoyed me enough to do it.
diff --git a/googlemovies.pl b/googlemovies.pl index 3535d6e..a9c2fc0 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,106 +1,111 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; +use XML::Writer; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode to use from the args my $postcode = join '', @ARGV; $postcode =~ s/\s+//; my $googleurl = "http://www.google.com/movies?near="; my $url = $googleurl.$postcode; my $response = get($googleurl.$postcode); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?"; exit; } my $tree = HTML::TreeBuilder->new(); $tree->parse($response); $tree->eof; -print <<HEAD; -<?xml version="1.0" encoding="utf-8"?> -<MovieTimes> -HEAD +my $out = ''; +my $xml = new XML::Writer( + OUTPUT => $out, + DATA_MODE => 1, + DATA_INDENT => 4 +); + +$xml->xmlDecl(); +$xml->startTag('MovieTimes'); # The table isn't well structured, so we need to switch between # cinemas and movies as we come across them my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); foreach my $row (@rows) { if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { parse_cinema($cinema); } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { parse_movies(@movierows); } } -print <<END; -</Movies> -</Theater> -</MovieTimes> -END +$xml->endTag(); # Movies +$xml->endTag(); # Theater +$xml->endTag(); # MovieTimes +$xml->end(); +print $out; my $cinemaCount = 0; sub parse_cinema { my $cinema = shift; # We need to end the previous cinema block if we hit a new one if ($cinemaCount++ > 0) { - print "</Movies>\n</Theater>\n"; + $xml->endTag(); #Movies + $xml->endTag(); #Theater } - print "<Theater>\n"; + $xml->startTag('Theater'); my $name = decode_entities(($cinema->look_down('_tag', 'b'))[0]->as_text); - print "<Name>$name</Name>\n"; + $xml->dataElement('Name', $name); my $address = decode_entities(($cinema->look_down('_tag', 'font'))[0]->as_HTML); $address =~ m/>(.*) - [^<]+</; - print "<Address>$1</Address>\n"; + $xml->dataElement('Address', $1); - print "<Movies>\n"; + $xml->startTag('Movies'); } sub parse_movies { my @movierows = @_; foreach my $movierow (@movierows) { my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; if ($movie) { $movie = decode_entities($movie); + $xml->startTag('Movie'); - print "<Movie>\n"; - - if ((my $moviename) = ($movie =~ /<b.*?>(.*)<\/b>/i)) { - $moviename =~ s/&/&amp;/; - print "<Name>$moviename</Name>\n"; + if ($movie =~ /<b.*?>(.*)<\/b>/i) { + $xml->dataElement('Name', $1); } if ($movie =~ /Rated\s+(\w+)/i) { - print "<Rating>$1</Rating>\n"; + $xml->dataElement('Rating', $1); } if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { - print "<RunningTime>$1</RunningTime>\n"; + $xml->dataElement('RunningTime', $1); } if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { $showtimes =~ s/\s+/, /g; - print "<ShowTimes>$showtimes</ShowTimes>\n"; + $xml->dataElement('ShowTimes', $showtimes); } - print "</Movie>\n"; + $xml->endTag(); #Movie } } }
Jonty/Googlemovies
1c107668c2be29df69aae17e0acd9471dfb7661f
Escape the ampersands in titles
diff --git a/googlemovies.pl b/googlemovies.pl index 40d9a2f..3535d6e 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,105 +1,106 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode to use from the args my $postcode = join '', @ARGV; $postcode =~ s/\s+//; my $googleurl = "http://www.google.com/movies?near="; my $url = $googleurl.$postcode; my $response = get($googleurl.$postcode); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?"; exit; } my $tree = HTML::TreeBuilder->new(); $tree->parse($response); $tree->eof; print <<HEAD; <?xml version="1.0" encoding="utf-8"?> <MovieTimes> HEAD # The table isn't well structured, so we need to switch between # cinemas and movies as we come across them my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); foreach my $row (@rows) { if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { parse_cinema($cinema); } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { parse_movies(@movierows); } } print <<END; </Movies> </Theater> </MovieTimes> END my $cinemaCount = 0; sub parse_cinema { my $cinema = shift; # We need to end the previous cinema block if we hit a new one if ($cinemaCount++ > 0) { print "</Movies>\n</Theater>\n"; } print "<Theater>\n"; my $name = decode_entities(($cinema->look_down('_tag', 'b'))[0]->as_text); print "<Name>$name</Name>\n"; my $address = decode_entities(($cinema->look_down('_tag', 'font'))[0]->as_HTML); $address =~ m/>(.*) - [^<]+</; print "<Address>$1</Address>\n"; print "<Movies>\n"; } sub parse_movies { my @movierows = @_; foreach my $movierow (@movierows) { my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; if ($movie) { $movie = decode_entities($movie); print "<Movie>\n"; - if ($movie =~ /<b.*?>(.*)<\/b>/i) { - print "<Name>$1</Name>\n"; + if ((my $moviename) = ($movie =~ /<b.*?>(.*)<\/b>/i)) { + $moviename =~ s/&/&amp;/; + print "<Name>$moviename</Name>\n"; } if ($movie =~ /Rated\s+(\w+)/i) { print "<Rating>$1</Rating>\n"; } - if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-\s*/i) { + if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-/i) { print "<RunningTime>$1</RunningTime>\n"; } if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { $showtimes =~ s/\s+/, /g; print "<ShowTimes>$showtimes</ShowTimes>\n"; } print "</Movie>\n"; } } }
Jonty/Googlemovies
b790113455b29f67d68f14ee2f749d94ba4246d6
Useless line
diff --git a/googlemovies.pl b/googlemovies.pl index b414dbe..40d9a2f 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,106 +1,105 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; # Fetch the postcode to use from the args my $postcode = join '', @ARGV; $postcode =~ s/\s+//; my $googleurl = "http://www.google.com/movies?near="; my $url = $googleurl.$postcode; my $response = get($googleurl.$postcode); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?"; exit; } my $tree = HTML::TreeBuilder->new(); $tree->parse($response); $tree->eof; print <<HEAD; <?xml version="1.0" encoding="utf-8"?> <MovieTimes> HEAD # The table isn't well structured, so we need to switch between # cinemas and movies as we come across them my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); foreach my $row (@rows) { if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { parse_cinema($cinema); } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { parse_movies(@movierows); } } print <<END; </Movies> </Theater> </MovieTimes> END my $cinemaCount = 0; sub parse_cinema { my $cinema = shift; # We need to end the previous cinema block if we hit a new one if ($cinemaCount++ > 0) { print "</Movies>\n</Theater>\n"; } print "<Theater>\n"; my $name = decode_entities(($cinema->look_down('_tag', 'b'))[0]->as_text); print "<Name>$name</Name>\n"; my $address = decode_entities(($cinema->look_down('_tag', 'font'))[0]->as_HTML); $address =~ m/>(.*) - [^<]+</; print "<Address>$1</Address>\n"; print "<Movies>\n"; } sub parse_movies { my @movierows = @_; foreach my $movierow (@movierows) { my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; if ($movie) { $movie = decode_entities($movie); - $movie =~ s/&nbsp;/ /g; print "<Movie>\n"; if ($movie =~ /<b.*?>(.*)<\/b>/i) { print "<Name>$1</Name>\n"; } if ($movie =~ /Rated\s+(\w+)/i) { print "<Rating>$1</Rating>\n"; } if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-\s*/i) { print "<RunningTime>$1</RunningTime>\n"; } if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { $showtimes =~ s/\s+/, /g; print "<ShowTimes>$showtimes</ShowTimes>\n"; } print "</Movie>\n"; } } }
Jonty/Googlemovies
6bd2e45e3a7bb3743c07fe6bd4f6473d73875f7c
Minor comment
diff --git a/googlemovies.pl b/googlemovies.pl index c6321dc..b414dbe 100755 --- a/googlemovies.pl +++ b/googlemovies.pl @@ -1,105 +1,106 @@ #!/usr/bin/perl use warnings; use strict; use LWP::Simple; use HTML::Entities; use HTML::TreeBuilder; # Otherwise we can get complaints when unicode is output binmode STDOUT, ':utf8'; +# Fetch the postcode to use from the args my $postcode = join '', @ARGV; $postcode =~ s/\s+//; my $googleurl = "http://www.google.com/movies?near="; my $url = $googleurl.$postcode; my $response = get($googleurl.$postcode); if (!defined $response) { print "Failed to fetch movie times, did you pass a valid postcode?"; exit; } my $tree = HTML::TreeBuilder->new(); $tree->parse($response); $tree->eof; print <<HEAD; <?xml version="1.0" encoding="utf-8"?> <MovieTimes> HEAD # The table isn't well structured, so we need to switch between # cinemas and movies as we come across them my @rows = $tree->look_down('_tag', 'tr', valign => 'top'); foreach my $row (@rows) { if (my $cinema = $row->look_down('_tag', 'td', colspan => '4')) { parse_cinema($cinema); } elsif (my @movierows = $row->look_down('_tag', 'td', valign => 'top')) { parse_movies(@movierows); } } print <<END; </Movies> </Theater> </MovieTimes> END my $cinemaCount = 0; sub parse_cinema { my $cinema = shift; # We need to end the previous cinema block if we hit a new one if ($cinemaCount++ > 0) { print "</Movies>\n</Theater>\n"; } print "<Theater>\n"; my $name = decode_entities(($cinema->look_down('_tag', 'b'))[0]->as_text); print "<Name>$name</Name>\n"; my $address = decode_entities(($cinema->look_down('_tag', 'font'))[0]->as_HTML); $address =~ m/>(.*) - [^<]+</; print "<Address>$1</Address>\n"; print "<Movies>\n"; } sub parse_movies { my @movierows = @_; foreach my $movierow (@movierows) { my $movie = ($movierow->look_down('_tag', 'font'))[0]->as_HTML; if ($movie) { $movie = decode_entities($movie); $movie =~ s/&nbsp;/ /g; print "<Movie>\n"; if ($movie =~ /<b.*?>(.*)<\/b>/i) { print "<Name>$1</Name>\n"; } if ($movie =~ /Rated\s+(\w+)/i) { print "<Rating>$1</Rating>\n"; } if ($movie =~ /<br(?: \/)?>[^\w\s]*([\w\s]+)[^-]*-\s*/i) { print "<RunningTime>$1</RunningTime>\n"; } if ((my $showtimes) = ($movie =~ /^.*<br \/>(.*)<\/font>/i)) { $showtimes =~ s/\s+/, /g; print "<ShowTimes>$showtimes</ShowTimes>\n"; } print "</Movie>\n"; } } }
jaskorpe/CGI
30bb826cb05f2a6ef5c5b1fa12a5ea946a75c874
Fixed another xss vulnerability
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 8ef80cf..6359564 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,299 +1,300 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> #include "brainfuck_interpreter.h" static void header (char *title); static void footer (int exit_status); static char *valid_filename (char *name); static void main_site (void); static int file; static char *input; static int input_len; static char *tmp; static int code_len = 0; static char *code = 0; static char *code_start, *code_end; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); if (title) printf ("<head><title>%s</title>\n", title); else printf ("<head><title>Brainfuck interpreter</title>\n"); printf ("<meta http-equiv=\"content-type\"\n" "\tcontent=\"text/html;charset=utf-8\" />\n" - "<script type=\"text/javascript\" src=\"/functions.js\"></script>\n" + "<script type=\"text/javascript\"\n" + "\tsrc=\"http://mindmutation.net/functions.js\"></script>\n" "</head><body>\n"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>\n" "<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />\n" "<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">\n" "here</a>.</p><hr /><p>Version: 2.0WE (Web edition)</p><hr />\n" "<p><a href=\"http://validator.w3.org/check?uri=referer\">\n" "<img src=\"http://www.w3.org/Icons/valid-xhtml10\"\n" "\talt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\"" " /></a></p>" "</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if ((dp = opendir ("../brainfuck"))) { printf ("<p>Available files in /brainfuck:<br />\n"); while ((de = readdir (dp))) { if (de->d_type == DT_REG) { printf ("<a href=\"/brainfuck/%s\" " "onclick=\"loadBf('%s'); return false;\">" "%s</a><br />\n", de->d_name, de->d_name, de->d_name); } } } printf ("</p><form action=\"brainfuck.cgi\" id=\"bfForm\" " "method=\"post\"><p>\n" "<br />\n<textarea name=\"code\" id=\"bfcode\" " "rows=\"25\" cols=\"60\">+[,.]" "</textarea><br />\n<br />User supplied input:<br />" "<input type=\"text\" name=\"input\" /><br />\n" "<input type=\"submit\" value=\"Send\" /><br />\n" "<input type=\"reset\" value=\"Clear\" /><br />\n" "</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); code_start = code; code_end = code + code_len; if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (init_interpreter (code_len, code, input_len, input, print_cell) == -1) { if (errno == ENOMEM) printf ("<p>NOT ENOUGH MEMORIES!</p>"); else if (errno == EIO) printf ("<p>No code to interpret\n</p>"); else printf ("<p>Some undefined error occured\n</p>"); footer (EXIT_FAILURE); } if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n<p>Source code</a>:</p>"); printf ("<pre>"); code_start = code; code_end = code + code_len; while (code < code_end) - printf ("%c", *code++); + print_cell (*code++); printf ("</pre><hr />"); tmp = input; while (tmp && *tmp) print_cell (*tmp++); printf ("</pre><hr />"); printf ("<p>Output:</p><pre>\n\n"); if (interpret (0) == -1) { if (errno == ETIME) printf ("</pre>\n<p>Timeout!</p>"); else if (errno == EIO) printf ("\n\n</pre>\n<hr /><p>Trouble reading from input</p>"); else printf ("\n</pre>\n<hr /><p>Undefined error</p>"); footer (EXIT_FAILURE); } printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
be7cb9482284bea37617270006a50320b1994828
Fixed javascript
diff --git a/functions.js b/functions.js index 7e1a57e..63189c5 100644 --- a/functions.js +++ b/functions.js @@ -1,16 +1,17 @@ function loadBf(filename) { xmlhttp = new XMLHttpRequest (); xmlhttp.open("GET", "/brainfuck/" + filename, true); xmlhttp.onreadystatechange = stateChangeHandler; xmlhttp.send(null); function stateChangeHandler() { if (xmlhttp.readyState == 4) { - document.bfForm.code.value = xmlhttp.responseText; + code = document.getElementById ("bfcode"); + code.value = xmlhttp.responseText; } } } \ No newline at end of file
jaskorpe/CGI
d187df22ff41accaff37e5b15be001f35afe3bb0
Bumped to version 2.0WE
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index ba40a33..8ef80cf 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,299 +1,299 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> #include "brainfuck_interpreter.h" static void header (char *title); static void footer (int exit_status); static char *valid_filename (char *name); static void main_site (void); static int file; static char *input; static int input_len; static char *tmp; static int code_len = 0; static char *code = 0; static char *code_start, *code_end; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); if (title) printf ("<head><title>%s</title>\n", title); else printf ("<head><title>Brainfuck interpreter</title>\n"); printf ("<meta http-equiv=\"content-type\"\n" "\tcontent=\"text/html;charset=utf-8\" />\n" "<script type=\"text/javascript\" src=\"/functions.js\"></script>\n" "</head><body>\n"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>\n" "<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />\n" "<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">\n" - "here</a>.</p><hr /><p>Version: 1.1</p><hr />\n" + "here</a>.</p><hr /><p>Version: 2.0WE (Web edition)</p><hr />\n" "<p><a href=\"http://validator.w3.org/check?uri=referer\">\n" "<img src=\"http://www.w3.org/Icons/valid-xhtml10\"\n" "\talt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\"" " /></a></p>" "</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if ((dp = opendir ("../brainfuck"))) { printf ("<p>Available files in /brainfuck:<br />\n"); while ((de = readdir (dp))) { if (de->d_type == DT_REG) { printf ("<a href=\"/brainfuck/%s\" " "onclick=\"loadBf('%s'); return false;\">" "%s</a><br />\n", de->d_name, de->d_name, de->d_name); } } } printf ("</p><form action=\"brainfuck.cgi\" id=\"bfForm\" " "method=\"post\"><p>\n" "<br />\n<textarea name=\"code\" id=\"bfcode\" " "rows=\"25\" cols=\"60\">+[,.]" "</textarea><br />\n<br />User supplied input:<br />" "<input type=\"text\" name=\"input\" /><br />\n" "<input type=\"submit\" value=\"Send\" /><br />\n" "<input type=\"reset\" value=\"Clear\" /><br />\n" "</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); code_start = code; code_end = code + code_len; if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (init_interpreter (code_len, code, input_len, input, print_cell) == -1) { if (errno == ENOMEM) printf ("<p>NOT ENOUGH MEMORIES!</p>"); else if (errno == EIO) printf ("<p>No code to interpret\n</p>"); else printf ("<p>Some undefined error occured\n</p>"); footer (EXIT_FAILURE); } if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n<p>Source code</a>:</p>"); printf ("<pre>"); code_start = code; code_end = code + code_len; while (code < code_end) printf ("%c", *code++); printf ("</pre><hr />"); tmp = input; while (tmp && *tmp) print_cell (*tmp++); printf ("</pre><hr />"); printf ("<p>Output:</p><pre>\n\n"); if (interpret (0) == -1) { if (errno == ETIME) printf ("</pre>\n<p>Timeout!</p>"); else if (errno == EIO) printf ("\n\n</pre>\n<hr /><p>Trouble reading from input</p>"); else printf ("\n</pre>\n<hr /><p>Undefined error</p>"); footer (EXIT_FAILURE); } printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
74307b835dfa6fc66bb226f46a47cd60de8e0689
For some reason doing a make before committing did not seem like a good idea. Should be fixed now
diff --git a/Makefile b/Makefile index 6557921..9f055ac 100644 --- a/Makefile +++ b/Makefile @@ -1,14 +1,14 @@ CC=cc CFLAGS=-Wall -Wextra -c all: brainfuck.cgi -brainfuck.cgi: brainfuck.o +brainfuck.cgi: brainfuck.o brainfuck_interpreter.o $(CC) -o $@ $^ -lcgi brainfuck.o:brainfuck_cgi.c $(CC) $(CFLAGS) -c -o $@ $< clean: rm -f brainfuck.cgi *.o \ No newline at end of file diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index d19f350..ba40a33 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,298 +1,299 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> +#include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> #include "brainfuck_interpreter.h" static void header (char *title); static void footer (int exit_status); static char *valid_filename (char *name); static void main_site (void); static int file; static char *input; static int input_len; static char *tmp; static int code_len = 0; static char *code = 0; static char *code_start, *code_end; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); if (title) printf ("<head><title>%s</title>\n", title); else printf ("<head><title>Brainfuck interpreter</title>\n"); printf ("<meta http-equiv=\"content-type\"\n" "\tcontent=\"text/html;charset=utf-8\" />\n" "<script type=\"text/javascript\" src=\"/functions.js\"></script>\n" "</head><body>\n"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>\n" "<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />\n" "<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">\n" "here</a>.</p><hr /><p>Version: 1.1</p><hr />\n" "<p><a href=\"http://validator.w3.org/check?uri=referer\">\n" "<img src=\"http://www.w3.org/Icons/valid-xhtml10\"\n" "\talt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\"" " /></a></p>" "</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if ((dp = opendir ("../brainfuck"))) { printf ("<p>Available files in /brainfuck:<br />\n"); while ((de = readdir (dp))) { if (de->d_type == DT_REG) { printf ("<a href=\"/brainfuck/%s\" " "onclick=\"loadBf('%s'); return false;\">" "%s</a><br />\n", de->d_name, de->d_name, de->d_name); } } } printf ("</p><form action=\"brainfuck.cgi\" id=\"bfForm\" " "method=\"post\"><p>\n" "<br />\n<textarea name=\"code\" id=\"bfcode\" " "rows=\"25\" cols=\"60\">+[,.]" "</textarea><br />\n<br />User supplied input:<br />" "<input type=\"text\" name=\"input\" /><br />\n" "<input type=\"submit\" value=\"Send\" /><br />\n" "<input type=\"reset\" value=\"Clear\" /><br />\n" "</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); code_start = code; code_end = code + code_len; if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (init_interpreter (code_len, code, input_len, input, print_cell) == -1) { if (errno == ENOMEM) printf ("<p>NOT ENOUGH MEMORIES!</p>"); else if (errno == EIO) printf ("<p>No code to interpret\n</p>"); else printf ("<p>Some undefined error occured\n</p>"); footer (EXIT_FAILURE); } if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n<p>Source code</a>:</p>"); printf ("<pre>"); code_start = code; code_end = code + code_len; while (code < code_end) printf ("%c", *code++); printf ("</pre><hr />"); tmp = input; while (tmp && *tmp) print_cell (*tmp++); printf ("</pre><hr />"); printf ("<p>Output:</p><pre>\n\n"); if (interpret (0) == -1) { if (errno == ETIME) printf ("</pre>\n<p>Timeout!</p>"); else if (errno == EIO) printf ("\n\n</pre>\n<hr /><p>Trouble reading from input</p>"); else printf ("\n</pre>\n<hr /><p>Undefined error</p>"); footer (EXIT_FAILURE); } printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; } diff --git a/brainfuck_interpreter.c b/brainfuck_interpreter.c index 8712984..01d622c 100644 --- a/brainfuck_interpreter.c +++ b/brainfuck_interpreter.c @@ -1,169 +1,171 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <ctype.h> #include <errno.h> static char *input; static int input_len; static int i = 0; static unsigned char *cells; static unsigned int cell; static char *code = 0; static char *code_start; static char *code_end; static int code_len; static struct timeval stop_time; static struct timeval start_time; static struct timeval offset = {5, 0}; void default_print_cell (char c) { printf ("%c", c); } static void (*print_cell) (char) = default_print_cell; int init_interpreter (int c_len, char *c, int i_len, char *i, void (*cb) (char)) { if (!c_len && !c) { errno = EIO; return -1; } code_len = c_len; code = c; code_start = code; code_end = code + code_len; input_len = i_len; input = i; if (!(cells = malloc (30000))) { errno = ENOMEM; return -1; } cell = 0; memset (cells, 0, 30000); gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); if (cb) print_cell = cb; return 0; } int interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { errno = ETIME; return -1; } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; if (interpret (ignore) == -1) return -1; continue; } else if (instruction == ']') { return 0; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': print_cell (cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { errno = EIO; return -1; } break; case '[': if (cells[cell]) { i++; if (interpret (0) == -1) return -1; } else { i++; if (interpret (1) == -1) return -1; } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return 0; } break; } } + + return 0; }
jaskorpe/CGI
491ded48c70512f98febf60ad45033ca6ea22728
Split code interpretation into separate file.
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 4336b1c..ac9c3aa 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,396 +1,292 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> -#include <sys/time.h> -#include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> +#include "brainfuck_interpreter.h" -void interpret (int ignore); -void header (char *title); -void footer (int exit_status); -char *valid_filename (char *name); -void main_site (void); +static void header (char *title); +static void footer (int exit_status); +static char *valid_filename (char *name); +static void main_site (void); -struct timeval stop_time; -struct timeval start_time; -struct timeval offset = {5, 0}; -char *input; -int input_len; +static int file; -unsigned char *cells; -unsigned int cell; - -char *code = 0; -char *code_start; -char *code_end; -int code_len; - -int i; - -int file; +static char *input; +static int input_len; +static int code_len = 0; +static char *code = 0; +static char *code_start, *code_end; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } - -void -interpret (int ignore) -{ - int code_pos = i; - char instruction; - - - for (; code < code_end; i++) - { - - gettimeofday (&start_time, NULL); - - if (timercmp (&start_time, &stop_time, >)) - { - printf ("</pre><p>Timeout!</p>"); - footer (EXIT_FAILURE); - } - - instruction = *(code++); - - if (ignore) - { - if (instruction == '[') - { - i++; - interpret (ignore); - continue; - } - else if (instruction == ']') - { - return; - } - else - { - continue; - } - } - - switch (instruction) - { - case '>': - if (cell++ == 29999) - cell = 0; - break; - case '<': - if (cell-- == 0) - cell = 29999; - break; - case '+': - cells[cell]++; - break; - case '-': - cells[cell]--; - break; - case '.': - print_cell (cells[cell]); - break; - case ',': - if (input_len--) - cells[cell] = *(input++); - else - { - printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); - footer (EXIT_FAILURE); - } - break; - case '[': - if (cells[cell]) - { - i++; - interpret (0); - } - else - { - i++; - interpret (1); - } - break; - case ']': - if (cells[cell]) - { - code = code_start+code_pos; - i = code_pos-1; - } - else - { - return; - } - break; - } - } -} - - void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); if (title) printf ("<head><title>%s</title>\n", title); else printf ("<head><title>Brainfuck interpreter</title>\n"); printf ("<meta http-equiv=\"content-type\"\n" "\tcontent=\"text/html;charset=utf-8\" />\n" "<script type=\"text/javascript\" src=\"/functions.js\"></script>\n" "</head><body>\n"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>\n" "<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />\n" "<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">\n" "here</a>.</p><hr /><p>Version: 1.1</p><hr />\n" "<p><a href=\"http://validator.w3.org/check?uri=referer\">\n" "<img src=\"http://www.w3.org/Icons/valid-xhtml10\"\n" "\talt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\"" " /></a></p>" "</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if ((dp = opendir ("../brainfuck"))) { printf ("<p>Available files in /brainfuck:<br />\n"); while ((de = readdir (dp))) { if (de->d_type == DT_REG) { printf ("<a href=\"/brainfuck/%s\" " "onClick=\"loadBf('%s'); return false;\">" "%s</a><br />\n", de->d_name, de->d_name, de->d_name); } } } printf ("</p><form action=\"brainfuck.cgi\" name=\"bfForm\" " "method=\"post\"><p>\n" "<br />\n<textarea name=\"code\" " "rows=\"25\" cols=\"60\">+[,.]" "</textarea><br />\n<br />User supplied input:<br />" "<input type=\"text\" name=\"input\" /><br />\n" "<input type=\"submit\" value=\"Send\" /><br />\n" "<input type=\"reset\" value=\"Clear\" /><br />\n" "</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); - - if (!code) - { - printf ("<p>No code to interpret\n</p>"); - footer (EXIT_FAILURE); - } - code_start = code; code_end = code + code_len; - if (!(cells = malloc (30000))) + if ((input = cgiGetValue (cgi, "input"))) + input_len = strlen (input); + else + input_len = 0; + + + if (init_interpreter (code_len, code, input_len, input, print_cell) == -1) { - printf ("<p>NOT ENOUGH MEMORIES!</p>"); + if (errno == ENOMEM) + printf ("<p>NOT ENOUGH MEMORIES!</p>"); + else if (errno == EIO) + printf ("<p>No code to interpret\n</p>"); + else + printf ("<p>Some undefined error occured\n</p>"); + footer (EXIT_FAILURE); } - gettimeofday (&start_time, NULL); - timeradd (&start_time, &offset, &stop_time); - - cell = 0; - memset (cells, 0, 30000); - if ((input = cgiGetValue (cgi, "input"))) - input_len = strlen (input); - else - input_len = 0; if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else - printf ("\n\n</pre><p>Source code</a>:</p>"); + printf ("\n\n<p>Source code</a>:</p>"); printf ("<pre>"); - code = code_start; + + code_start = code; + code_end = code + code_len; while (code < code_end) printf ("%c", *code++); - code = code_start; - printf ("</pre><hr />"); if (input) printf ("Input:<pre>%s</pre><hr />", input); - i = 0; - printf ("<p>Output:</p><pre>\n\n"); - interpret (0); + if (interpret (0) == -1) + { + if (errno == ETIME) + printf ("</pre>\n<p>Timeout!</p>"); + else if (errno == EIO) + printf ("\n\n</pre>\n<hr /><p>Trouble reading from input</p>"); + else + printf ("\n</pre>\n<hr /><p>Undefined error</p>"); + footer (EXIT_FAILURE); + } printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; } diff --git a/brainfuck_interpreter.c b/brainfuck_interpreter.c new file mode 100644 index 0000000..8712984 --- /dev/null +++ b/brainfuck_interpreter.c @@ -0,0 +1,169 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include <sys/time.h> +#include <ctype.h> + +#include <errno.h> + + +static char *input; +static int input_len; + +static int i = 0; + +static unsigned char *cells; +static unsigned int cell; + +static char *code = 0; +static char *code_start; +static char *code_end; +static int code_len; + + +static struct timeval stop_time; +static struct timeval start_time; +static struct timeval offset = {5, 0}; + + +void +default_print_cell (char c) +{ + printf ("%c", c); +} + +static void (*print_cell) (char) = default_print_cell; + +int +init_interpreter (int c_len, char *c, int i_len, char *i, void (*cb) (char)) +{ + if (!c_len && !c) + { + errno = EIO; + return -1; + } + code_len = c_len; + code = c; + + code_start = code; + code_end = code + code_len; + + + input_len = i_len; + input = i; + + + if (!(cells = malloc (30000))) + { + errno = ENOMEM; + return -1; + } + cell = 0; + memset (cells, 0, 30000); + + + gettimeofday (&start_time, NULL); + timeradd (&start_time, &offset, &stop_time); + + if (cb) + print_cell = cb; + + return 0; +} + +int +interpret (int ignore) +{ + int code_pos = i; + char instruction; + + + for (; code < code_end; i++) + { + + gettimeofday (&start_time, NULL); + + if (timercmp (&start_time, &stop_time, >)) + { + errno = ETIME; + return -1; + } + + instruction = *(code++); + + if (ignore) + { + if (instruction == '[') + { + i++; + if (interpret (ignore) == -1) + return -1; + continue; + } + else if (instruction == ']') + { + return 0; + } + else + { + continue; + } + } + + switch (instruction) + { + case '>': + if (cell++ == 29999) + cell = 0; + break; + case '<': + if (cell-- == 0) + cell = 29999; + break; + case '+': + cells[cell]++; + break; + case '-': + cells[cell]--; + break; + case '.': + print_cell (cells[cell]); + break; + case ',': + if (input_len--) + cells[cell] = *(input++); + else + { + errno = EIO; + return -1; + } + break; + case '[': + if (cells[cell]) + { + i++; + if (interpret (0) == -1) + return -1; + } + else + { + i++; + if (interpret (1) == -1) + return -1; + } + break; + case ']': + if (cells[cell]) + { + code = code_start+code_pos; + i = code_pos-1; + } + else + { + return 0; + } + break; + } + } +} diff --git a/brainfuck_interpreter.h b/brainfuck_interpreter.h new file mode 100644 index 0000000..4e0c77a --- /dev/null +++ b/brainfuck_interpreter.h @@ -0,0 +1,7 @@ +int interpret (int ignore); + +int register_print_func (void (*cb) (char)); + +int init_interpreter (int code_len, char *code, + int input_len, char *input, + void (*cb) (char));
jaskorpe/CGI
9fac4490c289197e9a1211ad483106d1dfe2b61b
Fixed a segfault and added an id to textarea
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index eecabc5..e47b7ad 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,401 +1,401 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/time.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); struct timeval stop_time; struct timeval start_time; struct timeval offset = {5, 0}; char *input; int input_len; unsigned char *cells; unsigned int cell; char *code = 0; char *code_start; char *code_end; int code_len; int i; char *tmp; int file; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } void interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { printf ("</pre><p>Timeout!</p>"); footer (EXIT_FAILURE); } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': print_cell (cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); if (title) printf ("<head><title>%s</title>\n", title); else printf ("<head><title>Brainfuck interpreter</title>\n"); printf ("<meta http-equiv=\"content-type\"\n" "\tcontent=\"text/html;charset=utf-8\" />\n" "<script type=\"text/javascript\" src=\"/functions.js\"></script>\n" "</head><body>\n"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>\n" "<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />\n" "<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">\n" "here</a>.</p><hr /><p>Version: 1.1</p><hr />\n" "<p><a href=\"http://validator.w3.org/check?uri=referer\">\n" "<img src=\"http://www.w3.org/Icons/valid-xhtml10\"\n" "\talt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\"" " /></a></p>" "</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if ((dp = opendir ("../brainfuck"))) { printf ("<p>Available files in /brainfuck:<br />\n"); while ((de = readdir (dp))) { if (de->d_type == DT_REG) { printf ("<a href=\"/brainfuck/%s\" " - "onClick=\"loadBf('%s'); return false;\">" + "onclick=\"loadBf('%s'); return false;\">" "%s</a><br />\n", de->d_name, de->d_name, de->d_name); } } } - printf ("</p><form action=\"brainfuck.cgi\" name=\"bfForm\" " + printf ("</p><form action=\"brainfuck.cgi\" id=\"bfForm\" " "method=\"post\"><p>\n" - "<br />\n<textarea name=\"code\" " + "<br />\n<textarea name=\"code\" id=\"bfcode\" " "rows=\"25\" cols=\"60\">+[,.]" "</textarea><br />\n<br />User supplied input:<br />" "<input type=\"text\" name=\"input\" /><br />\n" "<input type=\"submit\" value=\"Send\" /><br />\n" "<input type=\"reset\" value=\"Clear\" /><br />\n" "</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); if (!code) { printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } code_start = code; code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); cell = 0; memset (cells, 0, 30000); if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n</pre><p>Source code</a>:</p>"); printf ("<pre>"); code = code_start; while (code < code_end) printf ("%c", *code++); code = code_start; printf ("</pre><hr />\nInput:<pre>\n"); tmp = input; - while (*tmp) + while (tmp && *tmp) print_cell (*tmp++); printf ("</pre><hr />"); i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
38f75e04132e83b4a29b7d95df7438a42fc47334
Fixed another xss problem
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 4336b1c..eecabc5 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,396 +1,401 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/time.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); struct timeval stop_time; struct timeval start_time; struct timeval offset = {5, 0}; char *input; int input_len; unsigned char *cells; unsigned int cell; char *code = 0; char *code_start; char *code_end; int code_len; int i; +char *tmp; + int file; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } void interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { printf ("</pre><p>Timeout!</p>"); footer (EXIT_FAILURE); } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': print_cell (cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); if (title) printf ("<head><title>%s</title>\n", title); else printf ("<head><title>Brainfuck interpreter</title>\n"); printf ("<meta http-equiv=\"content-type\"\n" "\tcontent=\"text/html;charset=utf-8\" />\n" "<script type=\"text/javascript\" src=\"/functions.js\"></script>\n" "</head><body>\n"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>\n" "<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />\n" "<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">\n" "here</a>.</p><hr /><p>Version: 1.1</p><hr />\n" "<p><a href=\"http://validator.w3.org/check?uri=referer\">\n" "<img src=\"http://www.w3.org/Icons/valid-xhtml10\"\n" "\talt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\"" " /></a></p>" "</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if ((dp = opendir ("../brainfuck"))) { printf ("<p>Available files in /brainfuck:<br />\n"); while ((de = readdir (dp))) { if (de->d_type == DT_REG) { printf ("<a href=\"/brainfuck/%s\" " "onClick=\"loadBf('%s'); return false;\">" "%s</a><br />\n", de->d_name, de->d_name, de->d_name); } } } printf ("</p><form action=\"brainfuck.cgi\" name=\"bfForm\" " "method=\"post\"><p>\n" "<br />\n<textarea name=\"code\" " "rows=\"25\" cols=\"60\">+[,.]" "</textarea><br />\n<br />User supplied input:<br />" "<input type=\"text\" name=\"input\" /><br />\n" "<input type=\"submit\" value=\"Send\" /><br />\n" "<input type=\"reset\" value=\"Clear\" /><br />\n" "</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); if (!code) { printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } code_start = code; code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); cell = 0; memset (cells, 0, 30000); if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n</pre><p>Source code</a>:</p>"); printf ("<pre>"); code = code_start; while (code < code_end) printf ("%c", *code++); code = code_start; - printf ("</pre><hr />"); + printf ("</pre><hr />\nInput:<pre>\n"); - if (input) - printf ("Input:<pre>%s</pre><hr />", input); + tmp = input; + while (*tmp) + print_cell (*tmp++); + + printf ("</pre><hr />"); i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
5c3c35c99b29d1af81c2fdcf52fa039cd5c27b5e
Added Makefile
diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..6557921 --- /dev/null +++ b/Makefile @@ -0,0 +1,14 @@ +CC=cc + +CFLAGS=-Wall -Wextra -c + +all: brainfuck.cgi + +brainfuck.cgi: brainfuck.o + $(CC) -o $@ $^ -lcgi + +brainfuck.o:brainfuck_cgi.c + $(CC) $(CFLAGS) -c -o $@ $< + +clean: + rm -f brainfuck.cgi *.o \ No newline at end of file
jaskorpe/CGI
f8de94271489409c0ca9cdcdfcb594864a047e2b
Added the javascript file
diff --git a/functions.js b/functions.js new file mode 100644 index 0000000..7e1a57e --- /dev/null +++ b/functions.js @@ -0,0 +1,16 @@ +function loadBf(filename) +{ + xmlhttp = new XMLHttpRequest (); + + xmlhttp.open("GET", "/brainfuck/" + filename, true); + xmlhttp.onreadystatechange = stateChangeHandler; + xmlhttp.send(null); + + function stateChangeHandler() + { + if (xmlhttp.readyState == 4) + { + document.bfForm.code.value = xmlhttp.responseText; + } + } +} \ No newline at end of file
jaskorpe/CGI
e9838ab0ef39fcacf5bb05a22c3271bde60b1e4b
Now with web2.0
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 89f99c6..4336b1c 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,394 +1,396 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/time.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); struct timeval stop_time; struct timeval start_time; struct timeval offset = {5, 0}; char *input; int input_len; unsigned char *cells; unsigned int cell; char *code = 0; char *code_start; char *code_end; int code_len; int i; int file; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } void interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { printf ("</pre><p>Timeout!</p>"); footer (EXIT_FAILURE); } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': print_cell (cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); if (title) printf ("<head><title>%s</title>\n", title); else printf ("<head><title>Brainfuck interpreter</title>\n"); printf ("<meta http-equiv=\"content-type\"\n" "\tcontent=\"text/html;charset=utf-8\" />\n" + "<script type=\"text/javascript\" src=\"/functions.js\"></script>\n" "</head><body>\n"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>\n" "<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />\n" "<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">\n" "here</a>.</p><hr /><p>Version: 1.1</p><hr />\n" "<p><a href=\"http://validator.w3.org/check?uri=referer\">\n" "<img src=\"http://www.w3.org/Icons/valid-xhtml10\"\n" "\talt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\"" " /></a></p>" "</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if ((dp = opendir ("../brainfuck"))) { printf ("<p>Available files in /brainfuck:<br />\n"); while ((de = readdir (dp))) { if (de->d_type == DT_REG) { - printf ("<a href=\"/brainfuck/%s\">" + printf ("<a href=\"/brainfuck/%s\" " + "onClick=\"loadBf('%s'); return false;\">" "%s</a><br />\n", de->d_name, de->d_name, de->d_name); } } } printf ("</p><form action=\"brainfuck.cgi\" name=\"bfForm\" " "method=\"post\"><p>\n" "<br />\n<textarea name=\"code\" " "rows=\"25\" cols=\"60\">+[,.]" "</textarea><br />\n<br />User supplied input:<br />" "<input type=\"text\" name=\"input\" /><br />\n" "<input type=\"submit\" value=\"Send\" /><br />\n" "<input type=\"reset\" value=\"Clear\" /><br />\n" "</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); if (!code) { printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } code_start = code; code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); cell = 0; memset (cells, 0, 30000); if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n</pre><p>Source code</a>:</p>"); printf ("<pre>"); code = code_start; while (code < code_end) printf ("%c", *code++); code = code_start; printf ("</pre><hr />"); if (input) printf ("Input:<pre>%s</pre><hr />", input); i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
6080b56cb773807982c7671b9ee464fb3a7a39c9
File type should now be DT_REG. Removed a couple of printfs
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 7b78048..89f99c6 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,407 +1,394 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/time.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); struct timeval stop_time; struct timeval start_time; struct timeval offset = {5, 0}; char *input; int input_len; unsigned char *cells; unsigned int cell; char *code = 0; char *code_start; char *code_end; int code_len; int i; int file; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } void interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { printf ("</pre><p>Timeout!</p>"); footer (EXIT_FAILURE); } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': print_cell (cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return; } break; } } } void header (char *title) { - printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); - printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); - - printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); + printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" + "\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"); if (title) - printf ("<head><title>%s</title>", title); + printf ("<head><title>%s</title>\n", title); else - printf ("<head><title>Brainfuck interpreter</title>"); + printf ("<head><title>Brainfuck interpreter</title>\n"); - printf ("<meta http-equiv=\"content-type\" "); - printf ("content=\"text/html;charset=utf-8\" />"); - printf ("</head><body>"); + printf ("<meta http-equiv=\"content-type\"\n" + "\tcontent=\"text/html;charset=utf-8\" />\n" + "</head><body>\n"); } void footer (int exit_status) { - printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); - printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); - - printf ("<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">"); - printf ("here</a>.</p><hr /><p>Version: 1.1</p><hr />\n"); + printf ("<hr /><p>Brainfuck interpreter completely written in C</p>\n" + "<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />\n" - printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); - printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); - printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" "); - printf ("/></a></p>"); + "<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">\n" + "here</a>.</p><hr /><p>Version: 1.1</p><hr />\n" + "<p><a href=\"http://validator.w3.org/check?uri=referer\">\n" + "<img src=\"http://www.w3.org/Icons/valid-xhtml10\"\n" + "\talt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\"" + " /></a></p>" - printf ("</body></html>"); + "</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; - char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if ((dp = opendir ("../brainfuck"))) { - printf ("<p>Available files in /brainfuck:</p>\n"); - - printf ("<form action=\"brainfuck.cgi\" method=\"post\"><p>\n"); + printf ("<p>Available files in /brainfuck:<br />\n"); while ((de = readdir (dp))) { - if (de->d_type == DT_UNKNOWN) + if (de->d_type == DT_REG) { - dup_name = tmp = strdup (de->d_name); - for (; *tmp != '.'; tmp++); - *tmp = '\0'; - printf ("<label>%s<input type=\"radio\" name=\"file\" value=\"%s\"/>", - de->d_name, dup_name); - printf ("</label><br />\n"); + printf ("<a href=\"/brainfuck/%s\">" + "%s</a><br />\n", + de->d_name, de->d_name, de->d_name); } } - printf ("<br />User supplied code (file selection takes precedence):"); - } - else - { - printf ("<form action=\"brainfuck.cgi\" method=\"post\"><p>\n"); } - printf ("<br />\n<textarea name=\"code\" rows=\"10\" cols=\"50\">+[,.]"); - printf ("</textarea><br />\n"); - - printf ("<br />User supplied input:<br />"); - printf ("<input type=\"text\" name=\"input\" /><br />\n"); - - printf ("<input type=\"submit\" value=\"Send\" /><br />\n"); - printf ("<input type=\"reset\" value=\"Clear\" /><br />\n"); + printf ("</p><form action=\"brainfuck.cgi\" name=\"bfForm\" " + "method=\"post\"><p>\n" + "<br />\n<textarea name=\"code\" " + "rows=\"25\" cols=\"60\">+[,.]" + "</textarea><br />\n<br />User supplied input:<br />" + "<input type=\"text\" name=\"input\" /><br />\n" + "<input type=\"submit\" value=\"Send\" /><br />\n" + "<input type=\"reset\" value=\"Clear\" /><br />\n" - printf ("</p></form>\n"); + "</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); if (!code) { printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } code_start = code; code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); cell = 0; memset (cells, 0, 30000); if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n</pre><p>Source code</a>:</p>"); printf ("<pre>"); code = code_start; while (code < code_end) printf ("%c", *code++); code = code_start; printf ("</pre><hr />"); if (input) printf ("Input:<pre>%s</pre><hr />", input); i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
c5fe108dceff05265b79d31d88f19bed95bd5dba
Fixed user interface.
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 9e79998..7b78048 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,406 +1,407 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/time.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); struct timeval stop_time; struct timeval start_time; struct timeval offset = {5, 0}; char *input; int input_len; unsigned char *cells; unsigned int cell; char *code = 0; char *code_start; char *code_end; int code_len; int i; int file; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } void interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { printf ("</pre><p>Timeout!</p>"); footer (EXIT_FAILURE); } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': print_cell (cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" "); printf ("content=\"text/html;charset=utf-8\" />"); printf ("</head><body>"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">"); printf ("here</a>.</p><hr /><p>Version: 1.1</p><hr />\n"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" "); printf ("/></a></p>"); printf ("</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); - if (!(dp = opendir ("../brainfuck"))) + if ((dp = opendir ("../brainfuck"))) { - printf ("<p>No available files</p>"); - footer (EXIT_FAILURE); - } - - printf ("<p>Available files in /brainfuck:</p>\n"); + printf ("<p>Available files in /brainfuck:</p>\n"); - printf ("<form action=\"brainfuck.cgi\" method=\"post\"><p>\n"); - while ((de = readdir (dp))) - { - if (de->d_type == DT_UNKNOWN) + printf ("<form action=\"brainfuck.cgi\" method=\"post\"><p>\n"); + while ((de = readdir (dp))) { - dup_name = tmp = strdup (de->d_name); - for (; *tmp != '.'; tmp++); - *tmp = '\0'; - printf ("<label>%s<input type=\"radio\" name=\"file\" value=\"%s\"/>", - de->d_name, dup_name); - printf ("</label><br />\n"); + if (de->d_type == DT_UNKNOWN) + { + dup_name = tmp = strdup (de->d_name); + for (; *tmp != '.'; tmp++); + *tmp = '\0'; + printf ("<label>%s<input type=\"radio\" name=\"file\" value=\"%s\"/>", + de->d_name, dup_name); + printf ("</label><br />\n"); + } } + printf ("<br />User supplied code (file selection takes precedence):"); + } + else + { + printf ("<form action=\"brainfuck.cgi\" method=\"post\"><p>\n"); } - printf ("<br />User supplied code (file selection takes precedence):"); printf ("<br />\n<textarea name=\"code\" rows=\"10\" cols=\"50\">+[,.]"); printf ("</textarea><br />\n"); printf ("<br />User supplied input:<br />"); printf ("<input type=\"text\" name=\"input\" /><br />\n"); printf ("<input type=\"submit\" value=\"Send\" /><br />\n"); printf ("<input type=\"reset\" value=\"Clear\" /><br />\n"); printf ("</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); if (!code) { printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } code_start = code; code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); cell = 0; memset (cells, 0, 30000); if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n</pre><p>Source code</a>:</p>"); printf ("<pre>"); code = code_start; while (code < code_end) printf ("%c", *code++); code = code_start; printf ("</pre><hr />"); if (input) printf ("Input:<pre>%s</pre><hr />", input); i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
9ad74f0bfb1735b96b3ef2e3077b44bc0bf6d550
Bumped version number
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 3ac2132..9e79998 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,406 +1,406 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/time.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); struct timeval stop_time; struct timeval start_time; struct timeval offset = {5, 0}; char *input; int input_len; unsigned char *cells; unsigned int cell; char *code = 0; char *code_start; char *code_end; int code_len; int i; int file; void print_cell (char c) { switch (c) { case '<': printf ("&lt;"); break; case '&': printf ("&amp;"); break; default: printf ("%c", c); break; } } void interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { printf ("</pre><p>Timeout!</p>"); footer (EXIT_FAILURE); } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': print_cell (cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" "); printf ("content=\"text/html;charset=utf-8\" />"); printf ("</head><body>"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">"); - printf ("here</a>.</p><hr /><p>Version: 1.0</p><hr />\n"); + printf ("here</a>.</p><hr /><p>Version: 1.1</p><hr />\n"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" "); printf ("/></a></p>"); printf ("</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if (!(dp = opendir ("../brainfuck"))) { printf ("<p>No available files</p>"); footer (EXIT_FAILURE); } printf ("<p>Available files in /brainfuck:</p>\n"); printf ("<form action=\"brainfuck.cgi\" method=\"post\"><p>\n"); while ((de = readdir (dp))) { if (de->d_type == DT_UNKNOWN) { dup_name = tmp = strdup (de->d_name); for (; *tmp != '.'; tmp++); *tmp = '\0'; printf ("<label>%s<input type=\"radio\" name=\"file\" value=\"%s\"/>", de->d_name, dup_name); printf ("</label><br />\n"); } } printf ("<br />User supplied code (file selection takes precedence):"); printf ("<br />\n<textarea name=\"code\" rows=\"10\" cols=\"50\">+[,.]"); printf ("</textarea><br />\n"); printf ("<br />User supplied input:<br />"); printf ("<input type=\"text\" name=\"input\" /><br />\n"); printf ("<input type=\"submit\" value=\"Send\" /><br />\n"); printf ("<input type=\"reset\" value=\"Clear\" /><br />\n"); printf ("</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); if (!code) { printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } code_start = code; code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); cell = 0; memset (cells, 0, 30000); if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n</pre><p>Source code</a>:</p>"); printf ("<pre>"); code = code_start; while (code < code_end) printf ("%c", *code++); code = code_start; printf ("</pre><hr />"); if (input) printf ("Input:<pre>%s</pre><hr />", input); i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
da8c9f865c30be7cd6fedbf9c3179c7a6a1fa3d7
Fixed a xss vulnerability. Thanks to Morten at PING for noticing it.
diff --git a/README b/README index 00075a2..7662b0f 100644 --- a/README +++ b/README @@ -1,20 +1,26 @@ Copyright (C) 2010 Jon Anders Skorpen CGI Brainfuck interpreter in C How to use: Compile by doing gcc -o brainfuck.cgi brainfuck_cgi.c -lcgi Deploy If you have libcgi in a strange location you might have to use -L, -I -and -static also. +and/or -static also. + + +Licence: +AGPL v3 TODO: Quine detection WEB2.0 :p Clean up some messy code +Cloud computing API :p (not really) + TODONE: Run code from unsecure sources Input \ No newline at end of file diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 0585038..3ac2132 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,388 +1,406 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/time.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); struct timeval stop_time; struct timeval start_time; struct timeval offset = {5, 0}; char *input; int input_len; unsigned char *cells; unsigned int cell; char *code = 0; char *code_start; char *code_end; int code_len; int i; int file; +void +print_cell (char c) +{ + switch (c) + { + case '<': + printf ("&lt;"); + break; + case '&': + printf ("&amp;"); + break; + default: + printf ("%c", c); + break; + } +} + + void interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { printf ("</pre><p>Timeout!</p>"); footer (EXIT_FAILURE); } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': - printf ("%c", cells[cell]); + print_cell (cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" "); printf ("content=\"text/html;charset=utf-8\" />"); printf ("</head><body>"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">"); printf ("here</a>.</p><hr /><p>Version: 1.0</p><hr />\n"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" "); printf ("/></a></p>"); printf ("</body></html>"); if (file) { munmap (code_start, code_len); close (file); } exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if (!(dp = opendir ("../brainfuck"))) { printf ("<p>No available files</p>"); footer (EXIT_FAILURE); } printf ("<p>Available files in /brainfuck:</p>\n"); printf ("<form action=\"brainfuck.cgi\" method=\"post\"><p>\n"); while ((de = readdir (dp))) { if (de->d_type == DT_UNKNOWN) { dup_name = tmp = strdup (de->d_name); for (; *tmp != '.'; tmp++); *tmp = '\0'; printf ("<label>%s<input type=\"radio\" name=\"file\" value=\"%s\"/>", de->d_name, dup_name); printf ("</label><br />\n"); } } printf ("<br />User supplied code (file selection takes precedence):"); printf ("<br />\n<textarea name=\"code\" rows=\"10\" cols=\"50\">+[,.]"); printf ("</textarea><br />\n"); printf ("<br />User supplied input:<br />"); printf ("<input type=\"text\" name=\"input\" /><br />\n"); printf ("<input type=\"submit\" value=\"Send\" /><br />\n"); printf ("<input type=\"reset\" value=\"Clear\" /><br />\n"); printf ("</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); if (!code) { printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } code_start = code; code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); cell = 0; memset (cells, 0, 30000); if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n</pre><p>Source code</a>:</p>"); printf ("<pre>"); code = code_start; while (code < code_end) printf ("%c", *code++); code = code_start; printf ("</pre><hr />"); if (input) printf ("Input:<pre>%s</pre><hr />", input); i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("</pre>\n\n"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
bc4dc46328a42c04294a1cf3c4e2da3a465fbd82
Remember to close file handle
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index b059977..0585038 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,384 +1,388 @@ /* Copyright (C) 2010 Jon Anders Skorpen * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/time.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); struct timeval stop_time; struct timeval start_time; struct timeval offset = {5, 0}; char *input; int input_len; unsigned char *cells; unsigned int cell; char *code = 0; char *code_start; char *code_end; int code_len; int i; int file; void interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { printf ("</pre><p>Timeout!</p>"); footer (EXIT_FAILURE); } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" "); printf ("content=\"text/html;charset=utf-8\" />"); printf ("</head><body>"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">"); printf ("here</a>.</p><hr /><p>Version: 1.0</p><hr />\n"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" "); printf ("/></a></p>"); printf ("</body></html>"); + + if (file) + { + munmap (code_start, code_len); + close (file); + } + exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if (!(dp = opendir ("../brainfuck"))) { printf ("<p>No available files</p>"); footer (EXIT_FAILURE); } printf ("<p>Available files in /brainfuck:</p>\n"); printf ("<form action=\"brainfuck.cgi\" method=\"post\"><p>\n"); while ((de = readdir (dp))) { if (de->d_type == DT_UNKNOWN) { dup_name = tmp = strdup (de->d_name); for (; *tmp != '.'; tmp++); *tmp = '\0'; printf ("<label>%s<input type=\"radio\" name=\"file\" value=\"%s\"/>", de->d_name, dup_name); printf ("</label><br />\n"); } } printf ("<br />User supplied code (file selection takes precedence):"); printf ("<br />\n<textarea name=\"code\" rows=\"10\" cols=\"50\">+[,.]"); printf ("</textarea><br />\n"); printf ("<br />User supplied input:<br />"); printf ("<input type=\"text\" name=\"input\" /><br />\n"); printf ("<input type=\"submit\" value=\"Send\" /><br />\n"); printf ("<input type=\"reset\" value=\"Clear\" /><br />\n"); printf ("</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); if (!code) { printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } code_start = code; code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); cell = 0; memset (cells, 0, 30000); if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; if (filename) printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else printf ("\n\n</pre><p>Source code</a>:</p>"); printf ("<pre>"); code = code_start; while (code < code_end) printf ("%c", *code++); code = code_start; printf ("</pre><hr />"); if (input) printf ("Input:<pre>%s</pre><hr />", input); i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("</pre>\n\n"); - if (filename) - munmap (code, code_len); - footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
a5c537a2bf73779ef678ffe4bdc480e127efe599
Forgot to commit README
diff --git a/README b/README index 283ad3e..00075a2 100644 --- a/README +++ b/README @@ -1,19 +1,20 @@ Copyright (C) 2010 Jon Anders Skorpen CGI Brainfuck interpreter in C -Filename in get variable file, and input to brainfuck in get variable -input. - How to use: Compile by doing gcc -o brainfuck.cgi brainfuck_cgi.c -lcgi Deploy If you have libcgi in a strange location you might have to use -L, -I and -static also. TODO: -Run code from unsecure sources Quine detection -WEB2.0 :p \ No newline at end of file +WEB2.0 :p +Clean up some messy code + +TODONE: +Run code from unsecure sources +Input \ No newline at end of file
jaskorpe/CGI
3dcf35da222ba84ba64052f66d9ea43c64a935be
Bumped to version 1.0. Fixed some html bugs. Everything now under AGPL v3
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 09ed3d4..b059977 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,357 +1,384 @@ /* Copyright (C) 2010 Jon Anders Skorpen + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. */ + #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/time.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> #include <sys/mman.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); struct timeval stop_time; struct timeval start_time; struct timeval offset = {5, 0}; char *input; int input_len; unsigned char *cells; unsigned int cell; char *code = 0; char *code_start; char *code_end; int code_len; int i; int file; void interpret (int ignore) { int code_pos = i; char instruction; for (; code < code_end; i++) { gettimeofday (&start_time, NULL); if (timercmp (&start_time, &stop_time, >)) { printf ("</pre><p>Timeout!</p>"); footer (EXIT_FAILURE); } instruction = *(code++); if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { code = code_start+code_pos; i = code_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" "); printf ("content=\"text/html;charset=utf-8\" />"); + printf ("</head><body>"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); + printf ("<p>Get source code <a href=\"http://github.com/jaskorpe/CGI\">"); + printf ("here</a>.</p><hr /><p>Version: 1.0</p><hr />\n"); + printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" "); printf ("/></a></p>"); printf ("</body></html>"); exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if (!(dp = opendir ("../brainfuck"))) { printf ("<p>No available files</p>"); footer (EXIT_FAILURE); } printf ("<p>Available files in /brainfuck:</p>\n"); - printf ("<form action=\"brainfuck.cgi\" method=\"post\">\n"); + printf ("<form action=\"brainfuck.cgi\" method=\"post\"><p>\n"); while ((de = readdir (dp))) { if (de->d_type == DT_UNKNOWN) { dup_name = tmp = strdup (de->d_name); for (; *tmp != '.'; tmp++); *tmp = '\0'; - printf ("<input type=\"radio\" name=\"file\" value=\"%s\"/>%s<br />\n", - dup_name, de->d_name); + printf ("<label>%s<input type=\"radio\" name=\"file\" value=\"%s\"/>", + de->d_name, dup_name); + printf ("</label><br />\n"); } } - printf ("<br />User supplied code (file selection takes precedence):<br />\n"); - printf ("<textarea name=\"code\">+[-]</textarea><br />\n"); + printf ("<br />User supplied code (file selection takes precedence):"); + printf ("<br />\n<textarea name=\"code\" rows=\"10\" cols=\"50\">+[,.]"); + printf ("</textarea><br />\n"); printf ("<br />User supplied input:<br />"); printf ("<input type=\"text\" name=\"input\" /><br />\n"); printf ("<input type=\"submit\" value=\"Send\" /><br />\n"); printf ("<input type=\"reset\" value=\"Clear\" /><br />\n"); - printf ("</form>\n"); + printf ("</p></form>\n"); } int main (void) { char *filename; s_cgi *cgi; struct stat sb; cgi = cgiInit (); cgiHeader (); if ((filename = cgiGetValue (cgi, "file"))) header (filename); else if ((code = cgiGetValue (cgi, "code"))) header ("User supplied code"); else { header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } filename = (valid_filename (filename)); if (filename) { if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (fstat (file, &sb) == -1) { printf ("<p>Problem getting file lenght</p>\n"); footer (EXIT_FAILURE); } code_len = sb.st_size; if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) == MAP_FAILED) { printf ("<p>Problem memory mapping file</p>\n"); footer (EXIT_FAILURE); } } else if (code) code_len = strlen (code); if (!code) { printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } code_start = code; code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } gettimeofday (&start_time, NULL); timeradd (&start_time, &offset, &stop_time); cell = 0; memset (cells, 0, 30000); if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; - i = 0; - - printf ("<p>Output:</p><pre>\n\n"); - interpret (0); - if (filename) - printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a>:</p>", + printf ("\n\n<p><a href=\"/%s\">Source code</a>:</p>", filename+3); else - printf ("\n\n</pre><hr /><p>Source code</a>:</p>"); + printf ("\n\n</pre><p>Source code</a>:</p>"); printf ("<pre>"); code = code_start; while (code < code_end) printf ("%c", *code++); - printf ("</pre>"); + code = code_start; + + printf ("</pre><hr />"); + + if (input) + printf ("Input:<pre>%s</pre><hr />", input); + + + i = 0; + + printf ("<p>Output:</p><pre>\n\n"); + interpret (0); + + printf ("</pre>\n\n"); if (filename) munmap (code, code_len); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
c760fc119c0404780fcbb1531695e90d951db351
Bumped to version 1.0. Fixed some html bugs. Everything now under AGPL v3
diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..dba13ed --- /dev/null +++ b/COPYING @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<http://www.gnu.org/licenses/>.
jaskorpe/CGI
d8abc0a8c9e6c57734b130195a74f1c7cdf94925
A lot of changes. Input is now supported. User supplied code will also run. Execution is stopped after 5 seconds. Also a new UI
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 6cb1039..09ed3d4 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,298 +1,357 @@ /* Copyright (C) 2010 Jon Anders Skorpen */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> +#include <sys/time.h> + #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> +#include <sys/mman.h> + void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); +struct timeval stop_time; +struct timeval start_time; +struct timeval offset = {5, 0}; + char *input; int input_len; unsigned char *cells; unsigned int cell; + +char *code = 0; +char *code_start; +char *code_end; +int code_len; + int i; int file; void interpret (int ignore) { - int file_pos = i; + int code_pos = i; char instruction; - for (; read (file, &instruction, 1); i++) + for (; code < code_end; i++) { + + gettimeofday (&start_time, NULL); + + if (timercmp (&start_time, &stop_time, >)) + { + printf ("</pre><p>Timeout!</p>"); + footer (EXIT_FAILURE); + } + + instruction = *(code++); + if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { - lseek (file, file_pos, SEEK_SET); - i = file_pos-1; + code = code_start+code_pos; + i = code_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) - printf ("<head><title>/%s</title>", title); + printf ("<head><title>%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); - printf ("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />"); - - if (title) - printf ("</head><body><p>Interpreting file: /%s</p>", title); + printf ("<meta http-equiv=\"content-type\" "); + printf ("content=\"text/html;charset=utf-8\" />"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); - printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" /></a></p>"); + printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" "); + printf ("/></a></p>"); printf ("</body></html>"); exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if (!(dp = opendir ("../brainfuck"))) { printf ("<p>No available files</p>"); footer (EXIT_FAILURE); } - printf ("<p>Available files in /brainfuck:</p>"); + printf ("<p>Available files in /brainfuck:</p>\n"); - printf ("<ul>"); + printf ("<form action=\"brainfuck.cgi\" method=\"post\">\n"); while ((de = readdir (dp))) { if (de->d_type == DT_UNKNOWN) { dup_name = tmp = strdup (de->d_name); for (; *tmp != '.'; tmp++); *tmp = '\0'; - printf ("<li><a href=\"/cgi-bin/brainfuck.cgi?file=%s\">", - dup_name); - printf ("%s</a></li>", de->d_name); + printf ("<input type=\"radio\" name=\"file\" value=\"%s\"/>%s<br />\n", + dup_name, de->d_name); } } - printf ("</ul>"); + printf ("<br />User supplied code (file selection takes precedence):<br />\n"); + printf ("<textarea name=\"code\">+[-]</textarea><br />\n"); + + printf ("<br />User supplied input:<br />"); + printf ("<input type=\"text\" name=\"input\" /><br />\n"); + + printf ("<input type=\"submit\" value=\"Send\" /><br />\n"); + printf ("<input type=\"reset\" value=\"Clear\" /><br />\n"); + + printf ("</form>\n"); } int main (void) { char *filename; - char byte; - s_cgi *cgi; + struct stat sb; cgi = cgiInit (); cgiHeader (); - if (!(filename = cgiGetValue (cgi, "file"))) + if ((filename = cgiGetValue (cgi, "file"))) + header (filename); + else if ((code = cgiGetValue (cgi, "code"))) + header ("User supplied code"); + else { - header (NULL); + header ("Brainfuck interpreter"); main_site (); footer (EXIT_SUCCESS); } - cell = 0; - filename = (valid_filename (filename)); if (filename) - header (filename+3); - else - header (NULL); - - if (!filename) { - printf ("<p>No such file\n</p>"); - footer (EXIT_FAILURE); + if ((file = open (filename, O_RDONLY)) == -1) + { + printf ("<p>No such file: /%s</p>\n", filename+3); + footer (EXIT_FAILURE); + } + if (fstat (file, &sb) == -1) + { + printf ("<p>Problem getting file lenght</p>\n"); + footer (EXIT_FAILURE); + } + + code_len = sb.st_size; + + if ((code = mmap (NULL, code_len, PROT_READ, MAP_PRIVATE, file, 0)) + == MAP_FAILED) + { + printf ("<p>Problem memory mapping file</p>\n"); + footer (EXIT_FAILURE); + } } + else if (code) + code_len = strlen (code); + - if ((file = open (filename, O_RDONLY)) == -1) + if (!code) { - printf ("<p>No such file: /%s</p>\n", filename+3); + printf ("<p>No code to interpret\n</p>"); footer (EXIT_FAILURE); } + code_start = code; + code_end = code + code_len; if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } + gettimeofday (&start_time, NULL); + timeradd (&start_time, &offset, &stop_time); + + cell = 0; memset (cells, 0, 30000); - if (input = cgiGetValue (cgi, "input")) + if ((input = cgiGetValue (cgi, "input"))) input_len = strlen (input); else input_len = 0; i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); - printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a>:</p>", filename+3); - - - lseek (file, 0, SEEK_SET); + if (filename) + printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a>:</p>", + filename+3); + else + printf ("\n\n</pre><hr /><p>Source code</a>:</p>"); printf ("<pre>"); - while (read (file, &byte, 1)) - fwrite (&byte, 1, 1, stdout); + code = code_start; + while (code < code_end) + printf ("%c", *code++); printf ("</pre>"); + if (filename) + munmap (code, code_len); + footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
ab95f82c662873707cc91b05cb597d6bce6c312c
Added instruction on how to compile
diff --git a/README b/README index 944100f..283ad3e 100644 --- a/README +++ b/README @@ -1,11 +1,19 @@ Copyright (C) 2010 Jon Anders Skorpen CGI Brainfuck interpreter in C Filename in get variable file, and input to brainfuck in get variable input. +How to use: +Compile by doing gcc -o brainfuck.cgi brainfuck_cgi.c -lcgi +Deploy + +If you have libcgi in a strange location you might have to use -L, -I +and -static also. + + TODO: Run code from unsecure sources Quine detection WEB2.0 :p \ No newline at end of file
jaskorpe/CGI
b8041adaa5504208751ce225b22ed4a4722dda45
Added Copyright notice
diff --git a/README b/README index 8fd4ace..944100f 100644 --- a/README +++ b/README @@ -1 +1,11 @@ -CGI Brainfuck interpreter in C. No support for input yet. \ No newline at end of file +Copyright (C) 2010 Jon Anders Skorpen + +CGI Brainfuck interpreter in C + +Filename in get variable file, and input to brainfuck in get variable +input. + +TODO: +Run code from unsecure sources +Quine detection +WEB2.0 :p \ No newline at end of file diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 831c310..6cb1039 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,295 +1,298 @@ +/* Copyright (C) 2010 Jon Anders Skorpen + */ + #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> #include <errno.h> void interpret (int ignore); void header (char *title); void footer (int exit_status); char *valid_filename (char *name); void main_site (void); char *input; int input_len; unsigned char *cells; unsigned int cell; int i; int file; void interpret (int ignore) { int file_pos = i; char instruction; for (; read (file, &instruction, 1); i++) { if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': if (input_len--) cells[cell] = *(input++); else { printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); footer (EXIT_FAILURE); } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { lseek (file, file_pos, SEEK_SET); i = file_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>/%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />"); if (title) printf ("</head><body><p>Interpreting file: /%s</p>", title); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" /></a></p>"); printf ("</body></html>"); exit (exit_status); } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); if (!valid) return NULL; sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if (!(dp = opendir ("../brainfuck"))) { printf ("<p>No available files</p>"); footer (EXIT_FAILURE); } printf ("<p>Available files in /brainfuck:</p>"); printf ("<ul>"); while ((de = readdir (dp))) { if (de->d_type == DT_UNKNOWN) { dup_name = tmp = strdup (de->d_name); for (; *tmp != '.'; tmp++); *tmp = '\0'; printf ("<li><a href=\"/cgi-bin/brainfuck.cgi?file=%s\">", dup_name); printf ("%s</a></li>", de->d_name); } } printf ("</ul>"); } int main (void) { char *filename; char byte; s_cgi *cgi; cgi = cgiInit (); cgiHeader (); if (!(filename = cgiGetValue (cgi, "file"))) { header (NULL); main_site (); footer (EXIT_SUCCESS); } cell = 0; filename = (valid_filename (filename)); if (filename) header (filename+3); else header (NULL); if (!filename) { printf ("<p>No such file\n</p>"); footer (EXIT_FAILURE); } if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } memset (cells, 0, 30000); if (input = cgiGetValue (cgi, "input")) input_len = strlen (input); else input_len = 0; i = 0; printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a>:</p>", filename+3); lseek (file, 0, SEEK_SET); printf ("<pre>"); while (read (file, &byte, 1)) fwrite (&byte, 1, 1, stdout); printf ("</pre>"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
4c97d4b73d637f75a40de50e48f2ff29260fbefc
Added support for input. Fixed lots of small bugs, including html bugs and some pretty nasty security bugs
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 548d429..831c310 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,301 +1,295 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> #include <cgi.h> +#include <errno.h> + + +void interpret (int ignore); +void header (char *title); +void footer (int exit_status); +char *valid_filename (char *name); +void main_site (void); + + +char *input; +int input_len; unsigned char *cells; unsigned int cell; int i; + int file; void interpret (int ignore) { int file_pos = i; char instruction; for (; read (file, &instruction, 1); i++) { if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': + if (input_len--) + cells[cell] = *(input++); + else + { + printf ("\n\n</pre><hr /><p>Trouble reading from input</p>"); + footer (EXIT_FAILURE); + } break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { lseek (file, file_pos, SEEK_SET); i = file_pos-1; } else { return; } break; } } } void header (char *title) { printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>/%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />"); if (title) printf ("</head><body><p>Interpreting file: /%s</p>", title); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" /></a></p>"); printf ("</body></html>"); exit (exit_status); } - -char * -extract_get_var (char *get, char *name) -{ - char *value = NULL; - char *tmp; - - int i; - - if (!(tmp = strstr (get, name))) - return NULL; - - tmp += strlen (name); - - if (*tmp != '=') - return NULL; - - for (i = 0; *tmp != '&' && *tmp != '\0'; i++) - tmp++; - - value = malloc (i); - - memcpy (value, tmp-(i-1), i); - value[i-1] = '\0'; - - if (!*value) - { - free (value); - value = NULL; - } - - return value; -} - - char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); + + if (!valid) + return NULL; + sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if (!(dp = opendir ("../brainfuck"))) { printf ("<p>No available files</p>"); footer (EXIT_FAILURE); } printf ("<p>Available files in /brainfuck:</p>"); printf ("<ul>"); while ((de = readdir (dp))) { if (de->d_type == DT_UNKNOWN) { dup_name = tmp = strdup (de->d_name); for (; *tmp != '.'; tmp++); *tmp = '\0'; printf ("<li><a href=\"/cgi-bin/brainfuck.cgi?file=%s\">", dup_name); printf ("%s</a></li>", de->d_name); } } printf ("</ul>"); } int main (void) { char *filename; char byte; s_cgi *cgi; cgi = cgiInit (); cgiHeader (); if (!(filename = cgiGetValue (cgi, "file"))) { header (NULL); main_site (); footer (EXIT_SUCCESS); } cell = 0; filename = (valid_filename (filename)); if (filename) header (filename+3); else header (NULL); if (!filename) { printf ("<p>No such file\n</p>"); footer (EXIT_FAILURE); } if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } memset (cells, 0, 30000); + if (input = cgiGetValue (cgi, "input")) + input_len = strlen (input); + else + input_len = 0; + i = 0; - printf ("Output:<pre>\n\n"); + printf ("<p>Output:</p><pre>\n\n"); interpret (0); printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a>:</p>", filename+3); lseek (file, 0, SEEK_SET); printf ("<pre>"); while (read (file, &byte, 1)) fwrite (&byte, 1, 1, stdout); printf ("</pre>"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
55bf2043f7d36921d733cab829514d5da584c821
Use libcgi instead of badly written code
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index f277c5a..548d429 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,297 +1,301 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> +#include <cgi.h> + unsigned char *cells; unsigned int cell; int i; int file; void interpret (int ignore) { int file_pos = i; char instruction; for (; read (file, &instruction, 1); i++) { if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { lseek (file, file_pos, SEEK_SET); i = file_pos-1; } else { return; } break; } } } void header (char *title) { - printf ("Content-type: text/html\n\n"); - - printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>/%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />"); if (title) printf ("</head><body><p>Interpreting file: /%s</p>", title); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" /></a></p>"); printf ("</body></html>"); exit (exit_status); } char * extract_get_var (char *get, char *name) { char *value = NULL; char *tmp; int i; if (!(tmp = strstr (get, name))) return NULL; tmp += strlen (name); if (*tmp != '=') return NULL; for (i = 0; *tmp != '&' && *tmp != '\0'; i++) tmp++; value = malloc (i); memcpy (value, tmp-(i-1), i); value[i-1] = '\0'; if (!*value) { free (value); value = NULL; } return value; } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if (!(dp = opendir ("../brainfuck"))) { printf ("<p>No available files</p>"); footer (EXIT_FAILURE); } printf ("<p>Available files in /brainfuck:</p>"); printf ("<ul>"); while ((de = readdir (dp))) { if (de->d_type == DT_UNKNOWN) { dup_name = tmp = strdup (de->d_name); for (; *tmp != '.'; tmp++); *tmp = '\0'; printf ("<li><a href=\"/cgi-bin/brainfuck.cgi?file=%s\">", dup_name); printf ("%s</a></li>", de->d_name); } } printf ("</ul>"); } int main (void) { char *filename; - char *get = getenv ("QUERY_STRING"); char byte; - if (!*get) + s_cgi *cgi; + + + cgi = cgiInit (); + + cgiHeader (); + + if (!(filename = cgiGetValue (cgi, "file"))) { header (NULL); main_site (); footer (EXIT_SUCCESS); } cell = 0; - filename = extract_get_var (get, "file"); filename = (valid_filename (filename)); if (filename) header (filename+3); else header (NULL); if (!filename) { printf ("<p>No such file\n</p>"); footer (EXIT_FAILURE); } if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } memset (cells, 0, 30000); i = 0; printf ("Output:<pre>\n\n"); interpret (0); printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a>:</p>", filename+3); lseek (file, 0, SEEK_SET); printf ("<pre>"); while (read (file, &byte, 1)) fwrite (&byte, 1, 1, stdout); printf ("</pre>"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
0b701d97755d3cef8956509c3fb05e89dd6f5b90
Added readme
diff --git a/README b/README new file mode 100644 index 0000000..8fd4ace --- /dev/null +++ b/README @@ -0,0 +1 @@ +CGI Brainfuck interpreter in C. No support for input yet. \ No newline at end of file
jaskorpe/CGI
f05135870f15d52b6d21fca04e7387935620f64b
Added some new features and other small fixes
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index a5044dc..f277c5a 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,288 +1,297 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> unsigned char *cells; unsigned int cell; int i; int file; void interpret (int ignore) { int file_pos = i; char instruction; for (; read (file, &instruction, 1); i++) { if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { lseek (file, file_pos, SEEK_SET); i = file_pos-1; } else { return; } break; } } } void header (char *title) { printf ("Content-type: text/html\n\n"); printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>/%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />"); if (title) printf ("</head><body><p>Interpreting file: /%s</p>", title); - else - printf ("</head><body><p>No file to interpret</p>"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" /></a></p>"); printf ("</body></html>"); exit (exit_status); } char * extract_get_var (char *get, char *name) { char *value = NULL; char *tmp; int i; if (!(tmp = strstr (get, name))) return NULL; tmp += strlen (name); if (*tmp != '=') return NULL; for (i = 0; *tmp != '&' && *tmp != '\0'; i++) tmp++; value = malloc (i); memcpy (value, tmp-(i-1), i); value[i-1] = '\0'; if (!*value) { free (value); value = NULL; } return value; } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); sprintf (valid, "../brainfuck/%s.b", name); return valid; } void main_site (void) { DIR *dp; struct dirent *de; char *dup_name, *tmp; printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); if (!(dp = opendir ("../brainfuck"))) { printf ("<p>No available files</p>"); footer (EXIT_FAILURE); } printf ("<p>Available files in /brainfuck:</p>"); printf ("<ul>"); while ((de = readdir (dp))) { if (de->d_type == DT_UNKNOWN) { dup_name = tmp = strdup (de->d_name); for (; *tmp != '.'; tmp++); *tmp = '\0'; printf ("<li><a href=\"/cgi-bin/brainfuck.cgi?file=%s\">", dup_name); printf ("%s</a></li>", de->d_name); } } printf ("</ul>"); } int main (void) { char *filename; char *get = getenv ("QUERY_STRING"); + char byte; + if (!*get) { header (NULL); main_site (); footer (EXIT_SUCCESS); } cell = 0; filename = extract_get_var (get, "file"); filename = (valid_filename (filename)); if (filename) header (filename+3); else header (NULL); if (!filename) { printf ("<p>No such file\n</p>"); footer (EXIT_FAILURE); } if ((file = open (filename, O_RDONLY)) == -1) { printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (!(cells = malloc (30000))) { printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } memset (cells, 0, 30000); i = 0; - printf ("<pre>\n\n"); + printf ("Output:<pre>\n\n"); interpret (0); - printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a></p>", filename+3); + printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a>:</p>", filename+3); + + + lseek (file, 0, SEEK_SET); + + printf ("<pre>"); + while (read (file, &byte, 1)) + fwrite (&byte, 1, 1, stdout); + + printf ("</pre>"); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
bc1bd9d6faf7beaac06b5bd0d40e91218b74df21
Implementert browser
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index dcf8955..a5044dc 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,243 +1,288 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> +#include <dirent.h> #include <ctype.h> #include <fcntl.h> #include <unistd.h> unsigned char *cells; unsigned int cell; int i; int file; void interpret (int ignore) { int file_pos = i; char instruction; for (; read (file, &instruction, 1); i++) { if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { lseek (file, file_pos, SEEK_SET); i = file_pos-1; } else { return; } break; } } } void header (char *title) { printf ("Content-type: text/html\n\n"); printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); if (title) printf ("<head><title>/%s</title>", title); else printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />"); if (title) - printf ("</head><body><p>Interpreting file: %s</p><pre>\n\n", title); + printf ("</head><body><p>Interpreting file: /%s</p>", title); else printf ("</head><body><p>No file to interpret</p>"); } void footer (int exit_status) { printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); - printf ("alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" /></a></p>"); + printf (" alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" /></a></p>"); printf ("</body></html>"); exit (exit_status); } char * extract_get_var (char *get, char *name) { char *value = NULL; char *tmp; int i; if (!(tmp = strstr (get, name))) return NULL; tmp += strlen (name); if (*tmp != '=') return NULL; for (i = 0; *tmp != '&' && *tmp != '\0'; i++) tmp++; value = malloc (i); memcpy (value, tmp-(i-1), i); value[i-1] = '\0'; if (!*value) { free (value); value = NULL; } return value; } char * valid_filename (char *name) { char *tmp = name; char *valid; if (!tmp) return NULL; while (1) { if (*tmp == '\0') break;; if (!isupper (*tmp) && !islower (*tmp)) return NULL; tmp++; } valid = malloc (strlen (name) + 16); sprintf (valid, "../brainfuck/%s.b", name); return valid; } +void +main_site (void) +{ + DIR *dp; + struct dirent *de; + char *dup_name, *tmp; + + printf ("<p>Welcome to my Brainfuck online interpreter.</p>"); + + if (!(dp = opendir ("../brainfuck"))) + { + printf ("<p>No available files</p>"); + footer (EXIT_FAILURE); + } + + printf ("<p>Available files in /brainfuck:</p>"); + + printf ("<ul>"); + while ((de = readdir (dp))) + { + if (de->d_type == DT_UNKNOWN) + { + dup_name = tmp = strdup (de->d_name); + for (; *tmp != '.'; tmp++); + *tmp = '\0'; + printf ("<li><a href=\"/cgi-bin/brainfuck.cgi?file=%s\">", + dup_name); + printf ("%s</a></li>", de->d_name); + } + } + + printf ("</ul>"); +} + + int main (void) { char *filename; char *get = getenv ("QUERY_STRING"); + if (!*get) + { + header (NULL); + main_site (); + footer (EXIT_SUCCESS); + } + cell = 0; filename = extract_get_var (get, "file"); filename = (valid_filename (filename)); if (filename) header (filename+3); else header (NULL); if (!filename) { - printf ("No such file\n"); + printf ("<p>No such file\n</p>"); footer (EXIT_FAILURE); } if ((file = open (filename, O_RDONLY)) == -1) { - printf ("No such file: /%s\n", filename+3); + printf ("<p>No such file: /%s</p>\n", filename+3); footer (EXIT_FAILURE); } if (!(cells = malloc (30000))) { - printf ("NOT ENOUGH MEMORIES!"); + printf ("<p>NOT ENOUGH MEMORIES!</p>"); footer (EXIT_FAILURE); } memset (cells, 0, 30000); i = 0; + + printf ("<pre>\n\n"); interpret (0); printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a></p>", filename+3); footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
61aa01ab743f64650adae62d07c11d2a34c71238
All working. Input validation and everything else
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index e07c537..dcf8955 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,151 +1,243 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> +#include <ctype.h> #include <fcntl.h> #include <unistd.h> unsigned char *cells; unsigned int cell; int i; int file; void interpret (int ignore) { int file_pos = i; char instruction; for (; read (file, &instruction, 1); i++) { if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': break; case '[': if (cells[cell]) { i++; interpret (0); } else { i++; interpret (1); } break; case ']': if (cells[cell]) { lseek (file, file_pos, SEEK_SET); i = file_pos-1; } else { return; } break; } } } void header (char *title) { printf ("Content-type: text/html\n\n"); printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); - printf ("<head><title>%s</title>", title); + + if (title) + printf ("<head><title>/%s</title>", title); + else + printf ("<head><title>Brainfuck interpreter</title>"); printf ("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />"); - printf ("</head><body><pre>"); + + if (title) + printf ("</head><body><p>Interpreting file: %s</p><pre>\n\n", title); + else + printf ("</head><body><p>No file to interpret</p>"); } void footer (int exit_status) { - printf ("</pre><hr />"); + printf ("<hr /><p>Brainfuck interpreter completely written in C</p>"); + printf ("<p>Copyright (C) 2010 Jon Anders Skorpen</p><hr />"); + + printf ("<p><a href=\"http://validator.w3.org/check?uri=referer\">"); + printf ("<img src=\"http://www.w3.org/Icons/valid-xhtml10\""); + printf ("alt=\"Valid XHTML 1.0 Strict\" height=\"31\" width=\"88\" /></a></p>"); + + printf ("</body></html>"); exit (exit_status); } +char * +extract_get_var (char *get, char *name) +{ + char *value = NULL; + char *tmp; + + int i; + + if (!(tmp = strstr (get, name))) + return NULL; + + tmp += strlen (name); + + if (*tmp != '=') + return NULL; + + for (i = 0; *tmp != '&' && *tmp != '\0'; i++) + tmp++; + + value = malloc (i); + + memcpy (value, tmp-(i-1), i); + value[i-1] = '\0'; + + if (!*value) + { + free (value); + value = NULL; + } + + return value; +} + + +char * +valid_filename (char *name) +{ + char *tmp = name; + char *valid; + + if (!tmp) + return NULL; + + while (1) + { + if (*tmp == '\0') + break;; + + if (!isupper (*tmp) && !islower (*tmp)) + return NULL; + + tmp++; + } + + valid = malloc (strlen (name) + 16); + sprintf (valid, "../brainfuck/%s.b", name); + + return valid; +} + + int main (void) { - char *filename = getenv ("QUERY_STRING"); + char *filename; + char *get = getenv ("QUERY_STRING"); cell = 0; - header (filename); + filename = extract_get_var (get, "file"); + filename = (valid_filename (filename)); + + if (filename) + header (filename+3); + else + header (NULL); + + if (!filename) + { + printf ("No such file\n"); + footer (EXIT_FAILURE); + } if ((file = open (filename, O_RDONLY)) == -1) { - printf ("No such file: %s\n", filename); - footer (-1); + printf ("No such file: /%s\n", filename+3); + footer (EXIT_FAILURE); } if (!(cells = malloc (30000))) { printf ("NOT ENOUGH MEMORIES!"); - footer (-1); + footer (EXIT_FAILURE); } memset (cells, 0, 30000); i = 0; interpret (0); - footer (0); + printf ("\n\n</pre><hr /><p><a href=\"/%s\">Source code</a></p>", filename+3); + + footer (EXIT_SUCCESS); return 0; }
jaskorpe/CGI
dbd3a634c5421ab5fde38f5abbdab6539d6bd7af
Finished version 0.5. Now fully working. No support for stdin yet.
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index 3d4c190..e07c537 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,140 +1,151 @@ #include <stdio.h> #include <stdlib.h> +#include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> unsigned char *cells; unsigned int cell; int i; int file; void interpret (int ignore) { int file_pos = i; - int nest_count = 1; char instruction; for (; read (file, &instruction, 1); i++) { if (ignore) { if (instruction == '[') { i++; interpret (ignore); continue; } else if (instruction == ']') { return; } else { continue; } } switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': break; case '[': if (cells[cell]) { i++; interpret (0); - i--; } else { i++; interpret (1); } break; case ']': if (cells[cell]) { lseek (file, file_pos, SEEK_SET); - i = file_pos; + i = file_pos-1; } else { return; } break; } } } -int -main (void) +void +header (char *title) { - char *filename = getenv ("QUERY_STRING"); - cells = malloc (30000); - - - cell = 0; - printf ("Content-type: text/html\n\n"); printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); - printf ("<head><title>%s</title>", filename); + printf ("<head><title>%s</title>", title); printf ("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />"); printf ("</head><body><pre>"); +} + + +void +footer (int exit_status) +{ + printf ("</pre><hr />"); + printf ("</body></html>"); + exit (exit_status); +} + + +int +main (void) +{ + char *filename = getenv ("QUERY_STRING"); + + cell = 0; + + header (filename); - if (!(file = open (filename, O_RDONLY))) + if ((file = open (filename, O_RDONLY)) == -1) { - printf ("No such file: %s\n"); - goto end; - exit (-1); + printf ("No such file: %s\n", filename); + footer (-1); } if (!(cells = malloc (30000))) { - printf ("MEMORIES!"); - goto end; - exit (-1); + printf ("NOT ENOUGH MEMORIES!"); + footer (-1); } + memset (cells, 0, 30000); i = 0; interpret (0); - end: - printf ("</pre></body></html>"); + footer (0); return 0; }
jaskorpe/CGI
b85c6cbb82ed590b6e4d7453a5fdddc4d160dac9
Fungerer så og seie no. Nesten perfekt. No med ekte rekursjon
diff --git a/brainfuck_cgi.c b/brainfuck_cgi.c index a70b850..3d4c190 100644 --- a/brainfuck_cgi.c +++ b/brainfuck_cgi.c @@ -1,128 +1,140 @@ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> unsigned char *cells; unsigned int cell; int i; int file; void -interpret (void) +interpret (int ignore) { int file_pos = i; int nest_count = 1; char instruction; for (; read (file, &instruction, 1); i++) { + if (ignore) + { + if (instruction == '[') + { + i++; + interpret (ignore); + continue; + } + else if (instruction == ']') + { + return; + } + else + { + continue; + } + } + switch (instruction) { case '>': if (cell++ == 29999) cell = 0; break; case '<': if (cell-- == 0) cell = 29999; break; case '+': cells[cell]++; break; case '-': cells[cell]--; break; case '.': printf ("%c", cells[cell]); break; case ',': break; case '[': if (cells[cell]) { i++; - interpret (); + interpret (0); + i--; } else - for (; read (file, &instruction, 1); i++) - if (instruction == ']') - { - if (!(--nest_count)) - { - i++; - break; - } - } - else if (instruction == '[') - nest_count++; + { + i++; + interpret (1); + } break; case ']': if (cells[cell]) { lseek (file, file_pos, SEEK_SET); i = file_pos; } else { return; } break; } } } int main (void) { char *filename = getenv ("QUERY_STRING"); cells = malloc (30000); cell = 0; printf ("Content-type: text/html\n\n"); printf ("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""); printf ("\t\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"); printf ("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); printf ("<head><title>%s</title>", filename); printf ("<meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />"); printf ("</head><body><pre>"); if (!(file = open (filename, O_RDONLY))) { printf ("No such file: %s\n"); goto end; exit (-1); } if (!(cells = malloc (30000))) { printf ("MEMORIES!"); goto end; exit (-1); } i = 0; - interpret (); + interpret (0); end: printf ("</pre></body></html>"); return 0; }
pjkix/tumblr-dashboard-rss
f284b97a3c2ede101e02a65c4b00a10276e6d09a
[updated] minor cleanup, feed validation, etc
diff --git a/.htaccess b/.htaccess index 9856339..00d904a 100644 --- a/.htaccess +++ b/.htaccess @@ -1,5 +1,5 @@ # Protect files and directories -<Files ~ "(\.(conf|svn|git|inc|pl|sh|sql|tpl|ini)|Repositories|scripts|updates|_notes)$"> +<Files ~ "(\.(conf|svn|git|inc|sh|sql|tpl|ini)|Repositories|scripts|updates|_notes)$"> order deny,allow deny from all </Files> \ No newline at end of file diff --git a/README.md b/README.md index 8395586..3667059 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,51 @@ Tumblr Dashboard RSS ==================== - Author: - PJ Kix <[email protected]> - Version: - 1.1.0 - Copyright: - (cc) 2010 pjkix some rights reserved - License: - http://creativecommons.org/licenses/by-nc-nd/3.0/ - See Also: - http://www.tumblr.com/docs/en/api +Author: + PJ Kix <[email protected]> + +Version: + 1.1.0 + +Copyright: + (cc) 2010 pjkix some rights reserved + +License: + http://creativecommons.org/licenses/by-nc-nd/3.0/ + +See Also: + http://www.tumblr.com/docs/en/api Overview -------- This script uses the tumblr API to read the dashboard xml and then output an RSS feed. Usage ----- Upload the PHP script to a public location on a web server running PHP 5. Either a) edit the php script directly to set authentication or b) copy the config.ini.sample as config.ini and edit the settings. Todo ---- * make it more secure * multi-user friendly * content compression History ------- v1.1.0 (2011-05-17) * support for post types * support enclosure / media rss * support request caching * support output caching v1.0.4 (2010-02-01) * initial release * support for basic rss feed * support for http cache control header * support conditional get \ No newline at end of file diff --git a/tumblr-dashboard-rss.php b/tumblr-dashboard-rss.php index 57be108..00137b1 100644 --- a/tumblr-dashboard-rss.php +++ b/tumblr-dashboard-rss.php @@ -1,355 +1,358 @@ <?php /** * Tumblr Dashboard RSS Feed * * features: valid rss, cache-control, conditional get, easy config * requires: curl, dom, simplexml * @package Feeds * @author PJ Kix <[email protected]> * @copyright (cc) 2010 pjkix * @license http://creativecommons.org/licenses/by-nc-nd/3.0/ * @see http://www.tumblr.com/docs/en/api - * @version 1.2.0 $Id:$ + * @version 1.1.0 $Id:$ * @todo make it more secure, multi-user friendly, compression */ //* debug ini_set('display_errors', TRUE) ; error_reporting (E_ALL | E_STRICT) ; //*/ /** Authorization info */ $config['tumblr']['email'] = '[email protected]'; $config['tumblr']['password'] = 'password'; /** other settings*/ $config['DEBUG'] = FALSE; $config['cache']['request'] = TRUE; $config['cache']['output'] = TRUE; $config['cache']['ttl'] = '300'; // 5m in seconds $config['cache']['dir'] = './cache'; // make sure this is writeable for www server $config['cache']['request_file'] = 'dashboard.raw.xml'; $config['cache']['output_file'] = 'dashboard.rss.xml'; $config['feed']['img_size'] = 5; // 0-5 (0 is original or large, 5 is small) //$config['feed']['post_format'] = '[%1$s] %4$s (%2$s) - %3$s'; // [type] longname (shortname) - entry $config['feed']['post_format'] = '%3$s (%2$s) - %4$s [%1$s]'; // longname (shortname) - entry [type] /** read config ... if available */ if ( file_exists('config.ini') ) { $config = parse_ini_file('config.ini', TRUE); } // set GMT/UTC required for proper cache dates & feed validation date_default_timezone_set('GMT'); // and away we go ... if ($config['cache']['request'] && check_cache() ) { $result = file_get_contents($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file']); $posts = read_xml($result); output_rss($posts); } else { fetch_tumblr_dashboard_xml($config['tumblr']['email'], $config['tumblr']['password']); } /** Functions ------------------------------------- */ /** * Tumbler Dashboard API Read * * @param string $email tumblr account email address * @param string $password tumblr account password * @return void */ function fetch_tumblr_dashboard_xml($email, $password) { global $config; $config['DEBUG'] && error_log('[DEBUG] REQUESTING API READ!'); // Prepare POST request $request_data = http_build_query( array( 'email' => $email, 'password' => $password, 'generator' => 'tumblr Dashboard Feed 1.1', 'num' => '50' ) ); // Send the POST request (with cURL) $ch = curl_init('http://www.tumblr.com/api/dashboard'); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_USERAGENT, 'tumblr-dashboard-rss 1.1'); curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Check for success if ($status == 200) { // echo "Success! The output is $result.\n"; // do process/output $posts = read_xml($result); output_rss($posts); // cache xml file $config['cache']['request'] && cache_xml($result); } else if ($status == 403) { echo 'Bad email or password'; } else if ($status == 503) { echo 'Rate Limit Exceded or Service Down'; } else { echo "Error: $result\n"; } } /** * write xml to local file * @param type $result * @todo chose a cache method - raw or formatted */ function cache_xml($result) { global $config; if ( is_writable($config['cache']['dir']) ) { $fp = fopen($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file'], 'w'); fwrite($fp, $result); fclose($fp); } else { error_log('ERROR: xml cache not writeable'); return FALSE; } } /** * check if the cache is fresh * @param type $filename cache file path * @param type $ttl time in seconds * @return type bool true if file is fresh false if stale */ function check_cache() { global $config; $filename = $config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file']; $ttl = (int) $config['cache']['ttl']; // var_dump($filename, $ttl, filemtime($filename), time(), time() - $ttl);die; if (file_exists($filename) && filemtime($filename) + $ttl > time() ) { $config['DEBUG'] && error_log('[DEBUG] CACHE FOUND! AND NOT EXPIRED! :)'); return TRUE; } else { return FALSE; } } /** * parse tumblr dashboard xml * * @param string $result curl result string * @return array $posts array of posts for rss */ function read_xml($result) { global $config; $format = $config['feed']['post_format']; $img_size = (int)$config['feed']['img_size']; // $xml = simplexml_load_string($result); $xml = new SimpleXMLElement($result); // print_r($xml);die; // create simple array $posts = array(); foreach ($xml->posts->post as $post) { $item = array(); // var_dump($post);die; $item['title'] = str_replace('-', ' ', $post['slug']); // default $item['link'] = $post['url-with-slug']; $item['date'] = date(DATE_RSS, strtotime($post['date']) ); $item['description'] = $post['type']; // handle types [Text, Photo, Quote, Link, Chat, Audio, Video] switch($post['type']) { case 'regular': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'regular-title'} ) ; $item['description'] = $post->{'regular-body'}; break; case 'photo': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = sprintf('<img src="%s"/> %s', $post->{'photo-url'}[$img_size], $post->{'photo-caption'} ); $item['enclosure']['url'] = (string)$post->{'photo-url'}[0]; $item['enclosure']['type'] = 'image/jpg'; // FIXME: best guess ... whish i knew without checking extensions break; case 'quote': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = $post->{'quote-text'}; // var_dump($post);die; break; case 'answer': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = $post->answer; break; case 'link': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->link) ; $item['description'] = $post->link; break; case 'conversation': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'conversation-title'} ) ; $item['description'] = $post->{'conversation'}; break; case 'audio': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], strip_tags($post->{'audio-caption'} ) ) ; $item['description'] = $post->{'audio-player'} . $post->{'audio-caption'}; $item['enclosure']['url'] = $post->{'audio-download'}; $item['enclosure']['type'] = 'audio/mp3'; // FIXME: best guess without looking at extension break; case 'video': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = $post->{'video-player'}[0] . $post->{'video-caption'}; - $item['enclosure']['url'] = $post->{'video-source'}; - $item['enclosure']['type'] = 'video/mp4'; // FIXME: best guess without looking at extension + if ( preg_match('/https?:\/\/[^"]+/i', $post->{'video-source'}, $matches) ) + { + $item['enclosure']['url'] = $matches[0]; // must be full url + $item['enclosure']['type'] = 'video/mp4'; // FIXME: best guess without looking at extension + } break; default: $item['description'] = 'unknown post type: ' . $post['type']; break; } // append to array $posts[] = $item; } // var_dump($posts);die; return $posts; } /** * generate rss feed output * * @param array $items post item array * @return void */ function output_rss ($posts, $cache=false, $file=NULL) { global $config; if (!is_array($posts)) die('no posts ...'); $lastmod = strtotime($posts[0]['date']); // http headers - header('Content-type: text/xml'); // set mime ... application/rss+xml + header('Content-type: application/xml; charset=utf-8'); // set mime ... application/rss+xml header('Cache-Control: max-age=300, must-revalidate'); // cache control 5 mins header('Last-Modified: ' . gmdate('D, j M Y H:i:s T', $lastmod) ); //D, j M Y H:i:s T header('Expires: ' . gmdate('D, j M Y H:i:s T', time() + 300)); // conditional get ... $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === gmdate('D, j M Y H:i:s T', $lastmod) : FALSE; if ( FALSE !== $ifmod ) { $config['DEBUG'] && error_log('[DEBUG] 304 NOT MODIFIED :)'); header('HTTP/1.0 304 Not Modified'); exit; } // build rss using dom $dom = new DomDocument(); $dom->formatOutput = TRUE; $dom->encoding = 'utf-8'; $rss = $dom->createElement('rss'); $rss->setAttribute('version', '2.0'); $rss->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); // atom for self $rss->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/'); //xmlns:media="http://search.yahoo.com/mrss/" $dom->appendChild($rss); $channel = $dom->createElement('channel'); $rss->appendChild($channel); // set up feed properties $title = $dom->createElement('title', 'My Tumblr Dashboard Feed'); $channel->appendChild($title); $link = $dom->createElement('link', 'http://tumblr.com/dashboard'); $channel->appendChild($link); $description = $dom->createElement('description', 'My tumblr dashboard feed'); $channel->appendChild($description); $language = $dom->createElement('language', 'en-us'); $channel->appendChild($language); $pubDate = $dom->createElement('pubDate', $posts[0]['date'] ); $channel->appendChild($pubDate); $lastBuild = $dom->createElement('lastBuildDate', date(DATE_RSS) ); $channel->appendChild($lastBuild); $docs = $dom->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss' ); $channel->appendChild($docs); $generator = $dom->createElement('generator', 'Tumbler API' ); $channel->appendChild($generator); $managingEditor = $dom->createElement('managingEditor', '[email protected] (editor)' ); $channel->appendChild($managingEditor); $webMaster = $dom->createElement('webMaster', '[email protected] (webmaster)' ); $channel->appendChild($webMaster); $self = $dom->createElement('atom:link'); $self->setAttribute('href', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); $self->setAttribute('rel', 'self'); $self->setAttribute('type', 'application/rss+xml'); $channel->appendChild($self); // add items foreach( $posts as $post ) { $item = $dom->createElement('item'); $link = $dom->createElement('link', $post['link'] ); // $link->appendChild( $dom->createTextNode( $item['link'] ) ); $item->appendChild( $link ); $title = $dom->createElement('title', $post['title'] ); $item->appendChild( $title ); $description = $dom->createElement('description' ); // put description in cdata to avoid breakage $cdata = $dom->createCDATASection($post['description']); $description->appendChild($cdata); $item->appendChild( $description ); $pubDate = $dom->createElement('pubDate', $post['date'] ); $item->appendChild( $pubDate ); $guid = $dom->createElement('guid', $post['link'] ); $item->appendChild( $guid ); // if enclosure ... if ( isset($post['enclosure']) ) { //<enclosure url="http://www.webmonkey.com/monkeyrock.mpg" length="2471632" type="video/mpeg"/> $enclosure = $dom->createElement('enclosure'); $enclosure->setAttribute('url', $post['enclosure']['url']); $enclosure->setAttribute('length', '1024'); // this is required but doesn't need to be accurate $enclosure->setAttribute('type', $post['enclosure']['type']); // valid mime type $item->appendChild($enclosure); - // media rss + // media rss? } $channel->appendChild( $item ); } // cache output if ($config['cache']['output'] == TRUE && is_writable($config['cache']['dir'])) $dom->save($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['output_file']); // send output to browser echo $dom->saveXML(); } /*EOF*/
pjkix/tumblr-dashboard-rss
41b763663a16d44b35850b737a47c4ec64f7bd17
[changed] htaccess to use filesmatch [updated] regex for htaccess [updated] post types - fixed videos, quotes, etc
diff --git a/.htaccess b/.htaccess index 1e19b29..9856339 100644 --- a/.htaccess +++ b/.htaccess @@ -1,7 +1,5 @@ # Protect files and directories -#<Files ~ "\.(gif|jpe?g|png)$"> -#<FilesMatch "\.(gif|jpe?g|png)$"> -<Files ~ "(\.(conf|svn|git|inc|pl|sh|sql|tpl)|Repositories|scripts|updates|_notes|config.ini)$"> +<Files ~ "(\.(conf|svn|git|inc|pl|sh|sql|tpl|ini)|Repositories|scripts|updates|_notes)$"> order deny,allow deny from all </Files> \ No newline at end of file diff --git a/tumblr-dashboard-rss.php b/tumblr-dashboard-rss.php index d6c2dd8..57be108 100644 --- a/tumblr-dashboard-rss.php +++ b/tumblr-dashboard-rss.php @@ -1,355 +1,355 @@ <?php /** * Tumblr Dashboard RSS Feed * * features: valid rss, cache-control, conditional get, easy config * requires: curl, dom, simplexml * @package Feeds * @author PJ Kix <[email protected]> * @copyright (cc) 2010 pjkix * @license http://creativecommons.org/licenses/by-nc-nd/3.0/ * @see http://www.tumblr.com/docs/en/api * @version 1.2.0 $Id:$ * @todo make it more secure, multi-user friendly, compression */ //* debug ini_set('display_errors', TRUE) ; error_reporting (E_ALL | E_STRICT) ; //*/ /** Authorization info */ $config['tumblr']['email'] = '[email protected]'; $config['tumblr']['password'] = 'password'; /** other settings*/ $config['DEBUG'] = FALSE; $config['cache']['request'] = TRUE; $config['cache']['output'] = TRUE; $config['cache']['ttl'] = '300'; // 5m in seconds $config['cache']['dir'] = './cache'; // make sure this is writeable for www server $config['cache']['request_file'] = 'dashboard.raw.xml'; $config['cache']['output_file'] = 'dashboard.rss.xml'; $config['feed']['img_size'] = 5; // 0-5 (0 is original or large, 5 is small) //$config['feed']['post_format'] = '[%1$s] %4$s (%2$s) - %3$s'; // [type] longname (shortname) - entry $config['feed']['post_format'] = '%3$s (%2$s) - %4$s [%1$s]'; // longname (shortname) - entry [type] /** read config ... if available */ if ( file_exists('config.ini') ) { $config = parse_ini_file('config.ini', TRUE); } // set GMT/UTC required for proper cache dates & feed validation date_default_timezone_set('GMT'); // and away we go ... if ($config['cache']['request'] && check_cache() ) { $result = file_get_contents($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file']); $posts = read_xml($result); output_rss($posts); } else { fetch_tumblr_dashboard_xml($config['tumblr']['email'], $config['tumblr']['password']); } /** Functions ------------------------------------- */ /** * Tumbler Dashboard API Read * * @param string $email tumblr account email address * @param string $password tumblr account password * @return void */ function fetch_tumblr_dashboard_xml($email, $password) { global $config; $config['DEBUG'] && error_log('[DEBUG] REQUESTING API READ!'); // Prepare POST request $request_data = http_build_query( array( 'email' => $email, 'password' => $password, 'generator' => 'tumblr Dashboard Feed 1.1', 'num' => '50' ) ); // Send the POST request (with cURL) $ch = curl_init('http://www.tumblr.com/api/dashboard'); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_USERAGENT, 'tumblr-dashboard-rss 1.1'); curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Check for success if ($status == 200) { // echo "Success! The output is $result.\n"; // do process/output $posts = read_xml($result); output_rss($posts); - // cache xml file ... check last mod & serve static - cache_xml($result); + // cache xml file + $config['cache']['request'] && cache_xml($result); } else if ($status == 403) { echo 'Bad email or password'; } else if ($status == 503) { echo 'Rate Limit Exceded or Service Down'; } else { echo "Error: $result\n"; } } /** * write xml to local file * @param type $result * @todo chose a cache method - raw or formatted */ function cache_xml($result) { global $config; if ( is_writable($config['cache']['dir']) ) { $fp = fopen($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file'], 'w'); fwrite($fp, $result); fclose($fp); } else { error_log('ERROR: xml cache not writeable'); return FALSE; } } /** * check if the cache is fresh * @param type $filename cache file path * @param type $ttl time in seconds * @return type bool true if file is fresh false if stale */ function check_cache() { global $config; $filename = $config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file']; $ttl = (int) $config['cache']['ttl']; // var_dump($filename, $ttl, filemtime($filename), time(), time() - $ttl);die; if (file_exists($filename) && filemtime($filename) + $ttl > time() ) { $config['DEBUG'] && error_log('[DEBUG] CACHE FOUND! AND NOT EXPIRED! :)'); return TRUE; } else { return FALSE; } } /** * parse tumblr dashboard xml * * @param string $result curl result string * @return array $posts array of posts for rss */ function read_xml($result) { global $config; $format = $config['feed']['post_format']; $img_size = (int)$config['feed']['img_size']; // $xml = simplexml_load_string($result); $xml = new SimpleXMLElement($result); // print_r($xml);die; // create simple array $posts = array(); foreach ($xml->posts->post as $post) { $item = array(); // var_dump($post);die; $item['title'] = str_replace('-', ' ', $post['slug']); // default $item['link'] = $post['url-with-slug']; $item['date'] = date(DATE_RSS, strtotime($post['date']) ); $item['description'] = $post['type']; // handle types [Text, Photo, Quote, Link, Chat, Audio, Video] switch($post['type']) { case 'regular': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'regular-title'} ) ; $item['description'] = $post->{'regular-body'}; break; case 'photo': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = sprintf('<img src="%s"/> %s', $post->{'photo-url'}[$img_size], $post->{'photo-caption'} ); $item['enclosure']['url'] = (string)$post->{'photo-url'}[0]; $item['enclosure']['type'] = 'image/jpg'; // FIXME: best guess ... whish i knew without checking extensions -// var_dump($post);die; break; case 'quote': - $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->source) ; - $item['description'] = $post->quote; + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; + $item['description'] = $post->{'quote-text'}; + // var_dump($post);die; break; case 'answer': - $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slgu']) ; + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = $post->answer; break; case 'link': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->link) ; $item['description'] = $post->link; break; case 'conversation': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'conversation-title'} ) ; $item['description'] = $post->{'conversation'}; break; case 'audio': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], strip_tags($post->{'audio-caption'} ) ) ; $item['description'] = $post->{'audio-player'} . $post->{'audio-caption'}; $item['enclosure']['url'] = $post->{'audio-download'}; $item['enclosure']['type'] = 'audio/mp3'; // FIXME: best guess without looking at extension break; case 'video': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; - $item['description'] = 'Video ... embed goes here ... '; - $item['enclosure']['url'] = $post->{'video-download'}; + $item['description'] = $post->{'video-player'}[0] . $post->{'video-caption'}; + $item['enclosure']['url'] = $post->{'video-source'}; $item['enclosure']['type'] = 'video/mp4'; // FIXME: best guess without looking at extension break; default: $item['description'] = 'unknown post type: ' . $post['type']; break; } // append to array $posts[] = $item; } // var_dump($posts);die; return $posts; } /** * generate rss feed output * * @param array $items post item array * @return void */ function output_rss ($posts, $cache=false, $file=NULL) { global $config; if (!is_array($posts)) die('no posts ...'); $lastmod = strtotime($posts[0]['date']); // http headers header('Content-type: text/xml'); // set mime ... application/rss+xml header('Cache-Control: max-age=300, must-revalidate'); // cache control 5 mins header('Last-Modified: ' . gmdate('D, j M Y H:i:s T', $lastmod) ); //D, j M Y H:i:s T header('Expires: ' . gmdate('D, j M Y H:i:s T', time() + 300)); // conditional get ... $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === gmdate('D, j M Y H:i:s T', $lastmod) : FALSE; if ( FALSE !== $ifmod ) { $config['DEBUG'] && error_log('[DEBUG] 304 NOT MODIFIED :)'); header('HTTP/1.0 304 Not Modified'); exit; } // build rss using dom $dom = new DomDocument(); $dom->formatOutput = TRUE; $dom->encoding = 'utf-8'; $rss = $dom->createElement('rss'); $rss->setAttribute('version', '2.0'); $rss->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); // atom for self $rss->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/'); //xmlns:media="http://search.yahoo.com/mrss/" $dom->appendChild($rss); $channel = $dom->createElement('channel'); $rss->appendChild($channel); // set up feed properties $title = $dom->createElement('title', 'My Tumblr Dashboard Feed'); $channel->appendChild($title); $link = $dom->createElement('link', 'http://tumblr.com/dashboard'); $channel->appendChild($link); $description = $dom->createElement('description', 'My tumblr dashboard feed'); $channel->appendChild($description); $language = $dom->createElement('language', 'en-us'); $channel->appendChild($language); $pubDate = $dom->createElement('pubDate', $posts[0]['date'] ); $channel->appendChild($pubDate); $lastBuild = $dom->createElement('lastBuildDate', date(DATE_RSS) ); $channel->appendChild($lastBuild); $docs = $dom->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss' ); $channel->appendChild($docs); $generator = $dom->createElement('generator', 'Tumbler API' ); $channel->appendChild($generator); $managingEditor = $dom->createElement('managingEditor', '[email protected] (editor)' ); $channel->appendChild($managingEditor); $webMaster = $dom->createElement('webMaster', '[email protected] (webmaster)' ); $channel->appendChild($webMaster); $self = $dom->createElement('atom:link'); $self->setAttribute('href', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); $self->setAttribute('rel', 'self'); $self->setAttribute('type', 'application/rss+xml'); $channel->appendChild($self); // add items foreach( $posts as $post ) { $item = $dom->createElement('item'); $link = $dom->createElement('link', $post['link'] ); // $link->appendChild( $dom->createTextNode( $item['link'] ) ); $item->appendChild( $link ); $title = $dom->createElement('title', $post['title'] ); $item->appendChild( $title ); $description = $dom->createElement('description' ); // put description in cdata to avoid breakage $cdata = $dom->createCDATASection($post['description']); $description->appendChild($cdata); $item->appendChild( $description ); $pubDate = $dom->createElement('pubDate', $post['date'] ); $item->appendChild( $pubDate ); $guid = $dom->createElement('guid', $post['link'] ); $item->appendChild( $guid ); // if enclosure ... if ( isset($post['enclosure']) ) { //<enclosure url="http://www.webmonkey.com/monkeyrock.mpg" length="2471632" type="video/mpeg"/> $enclosure = $dom->createElement('enclosure'); $enclosure->setAttribute('url', $post['enclosure']['url']); $enclosure->setAttribute('length', '1024'); // this is required but doesn't need to be accurate $enclosure->setAttribute('type', $post['enclosure']['type']); // valid mime type $item->appendChild($enclosure); // media rss } $channel->appendChild( $item ); } // cache output if ($config['cache']['output'] == TRUE && is_writable($config['cache']['dir'])) $dom->save($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['output_file']); // send output to browser echo $dom->saveXML(); } /*EOF*/
pjkix/tumblr-dashboard-rss
c52cba241276d4001ac828af254b346daad76e46
[changed] cache check to actually work :) [added] debug messages
diff --git a/tumblr-dashboard-rss.php b/tumblr-dashboard-rss.php index 4ee017c..d6c2dd8 100644 --- a/tumblr-dashboard-rss.php +++ b/tumblr-dashboard-rss.php @@ -1,351 +1,355 @@ <?php /** * Tumblr Dashboard RSS Feed * * features: valid rss, cache-control, conditional get, easy config * requires: curl, dom, simplexml * @package Feeds * @author PJ Kix <[email protected]> * @copyright (cc) 2010 pjkix * @license http://creativecommons.org/licenses/by-nc-nd/3.0/ * @see http://www.tumblr.com/docs/en/api * @version 1.2.0 $Id:$ - * @todo post types, make it more secure, multi-user friendly, compression, cacheing + * @todo make it more secure, multi-user friendly, compression */ //* debug ini_set('display_errors', TRUE) ; error_reporting (E_ALL | E_STRICT) ; //*/ /** Authorization info */ $config['tumblr']['email'] = '[email protected]'; $config['tumblr']['password'] = 'password'; /** other settings*/ $config['DEBUG'] = FALSE; $config['cache']['request'] = TRUE; $config['cache']['output'] = TRUE; $config['cache']['ttl'] = '300'; // 5m in seconds $config['cache']['dir'] = './cache'; // make sure this is writeable for www server $config['cache']['request_file'] = 'dashboard.raw.xml'; $config['cache']['output_file'] = 'dashboard.rss.xml'; $config['feed']['img_size'] = 5; // 0-5 (0 is original or large, 5 is small) //$config['feed']['post_format'] = '[%1$s] %4$s (%2$s) - %3$s'; // [type] longname (shortname) - entry $config['feed']['post_format'] = '%3$s (%2$s) - %4$s [%1$s]'; // longname (shortname) - entry [type] /** read config ... if available */ if ( file_exists('config.ini') ) { $config = parse_ini_file('config.ini', TRUE); } // set GMT/UTC required for proper cache dates & feed validation date_default_timezone_set('GMT'); // and away we go ... if ($config['cache']['request'] && check_cache() ) { $result = file_get_contents($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file']); $posts = read_xml($result); output_rss($posts); } else { fetch_tumblr_dashboard_xml($config['tumblr']['email'], $config['tumblr']['password']); } /** Functions ------------------------------------- */ /** * Tumbler Dashboard API Read * * @param string $email tumblr account email address * @param string $password tumblr account password * @return void */ function fetch_tumblr_dashboard_xml($email, $password) { + global $config; + $config['DEBUG'] && error_log('[DEBUG] REQUESTING API READ!'); // Prepare POST request $request_data = http_build_query( array( 'email' => $email, 'password' => $password, 'generator' => 'tumblr Dashboard Feed 1.1', 'num' => '50' ) ); // Send the POST request (with cURL) $ch = curl_init('http://www.tumblr.com/api/dashboard'); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_USERAGENT, 'tumblr-dashboard-rss 1.1'); curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Check for success if ($status == 200) { // echo "Success! The output is $result.\n"; // do process/output $posts = read_xml($result); output_rss($posts); // cache xml file ... check last mod & serve static cache_xml($result); } else if ($status == 403) { echo 'Bad email or password'; } else if ($status == 503) { echo 'Rate Limit Exceded or Service Down'; } else { echo "Error: $result\n"; } } /** * write xml to local file * @param type $result * @todo chose a cache method - raw or formatted */ function cache_xml($result) { global $config; if ( is_writable($config['cache']['dir']) ) { $fp = fopen($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file'], 'w'); fwrite($fp, $result); fclose($fp); } else { error_log('ERROR: xml cache not writeable'); return FALSE; } } /** * check if the cache is fresh * @param type $filename cache file path * @param type $ttl time in seconds * @return type bool true if file is fresh false if stale */ function check_cache() { global $config; $filename = $config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file']; $ttl = (int) $config['cache']['ttl']; - if (file_exists($filename) && filemtime($filename) > time() - $ttl ) +// var_dump($filename, $ttl, filemtime($filename), time(), time() - $ttl);die; + + if (file_exists($filename) && filemtime($filename) + $ttl > time() ) { $config['DEBUG'] && error_log('[DEBUG] CACHE FOUND! AND NOT EXPIRED! :)'); return TRUE; } else { return FALSE; } } /** * parse tumblr dashboard xml * * @param string $result curl result string * @return array $posts array of posts for rss */ function read_xml($result) { global $config; $format = $config['feed']['post_format']; $img_size = (int)$config['feed']['img_size']; // $xml = simplexml_load_string($result); $xml = new SimpleXMLElement($result); // print_r($xml);die; // create simple array $posts = array(); foreach ($xml->posts->post as $post) { $item = array(); // var_dump($post);die; $item['title'] = str_replace('-', ' ', $post['slug']); // default $item['link'] = $post['url-with-slug']; $item['date'] = date(DATE_RSS, strtotime($post['date']) ); $item['description'] = $post['type']; // handle types [Text, Photo, Quote, Link, Chat, Audio, Video] switch($post['type']) { case 'regular': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'regular-title'} ) ; $item['description'] = $post->{'regular-body'}; break; case 'photo': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = sprintf('<img src="%s"/> %s', $post->{'photo-url'}[$img_size], $post->{'photo-caption'} ); $item['enclosure']['url'] = (string)$post->{'photo-url'}[0]; $item['enclosure']['type'] = 'image/jpg'; // FIXME: best guess ... whish i knew without checking extensions // var_dump($post);die; break; case 'quote': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->source) ; $item['description'] = $post->quote; break; case 'answer': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slgu']) ; $item['description'] = $post->answer; break; case 'link': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->link) ; $item['description'] = $post->link; break; case 'conversation': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'conversation-title'} ) ; $item['description'] = $post->{'conversation'}; break; case 'audio': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], strip_tags($post->{'audio-caption'} ) ) ; $item['description'] = $post->{'audio-player'} . $post->{'audio-caption'}; $item['enclosure']['url'] = $post->{'audio-download'}; $item['enclosure']['type'] = 'audio/mp3'; // FIXME: best guess without looking at extension break; case 'video': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = 'Video ... embed goes here ... '; $item['enclosure']['url'] = $post->{'video-download'}; $item['enclosure']['type'] = 'video/mp4'; // FIXME: best guess without looking at extension break; default: $item['description'] = 'unknown post type: ' . $post['type']; break; } // append to array $posts[] = $item; } // var_dump($posts);die; return $posts; } /** * generate rss feed output * * @param array $items post item array * @return void */ function output_rss ($posts, $cache=false, $file=NULL) { global $config; if (!is_array($posts)) die('no posts ...'); $lastmod = strtotime($posts[0]['date']); // http headers header('Content-type: text/xml'); // set mime ... application/rss+xml header('Cache-Control: max-age=300, must-revalidate'); // cache control 5 mins header('Last-Modified: ' . gmdate('D, j M Y H:i:s T', $lastmod) ); //D, j M Y H:i:s T header('Expires: ' . gmdate('D, j M Y H:i:s T', time() + 300)); // conditional get ... $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === gmdate('D, j M Y H:i:s T', $lastmod) : FALSE; if ( FALSE !== $ifmod ) { $config['DEBUG'] && error_log('[DEBUG] 304 NOT MODIFIED :)'); header('HTTP/1.0 304 Not Modified'); exit; } // build rss using dom $dom = new DomDocument(); $dom->formatOutput = TRUE; $dom->encoding = 'utf-8'; $rss = $dom->createElement('rss'); $rss->setAttribute('version', '2.0'); $rss->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); // atom for self $rss->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/'); //xmlns:media="http://search.yahoo.com/mrss/" $dom->appendChild($rss); $channel = $dom->createElement('channel'); $rss->appendChild($channel); // set up feed properties $title = $dom->createElement('title', 'My Tumblr Dashboard Feed'); $channel->appendChild($title); $link = $dom->createElement('link', 'http://tumblr.com/dashboard'); $channel->appendChild($link); $description = $dom->createElement('description', 'My tumblr dashboard feed'); $channel->appendChild($description); $language = $dom->createElement('language', 'en-us'); $channel->appendChild($language); $pubDate = $dom->createElement('pubDate', $posts[0]['date'] ); $channel->appendChild($pubDate); $lastBuild = $dom->createElement('lastBuildDate', date(DATE_RSS) ); $channel->appendChild($lastBuild); $docs = $dom->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss' ); $channel->appendChild($docs); $generator = $dom->createElement('generator', 'Tumbler API' ); $channel->appendChild($generator); $managingEditor = $dom->createElement('managingEditor', '[email protected] (editor)' ); $channel->appendChild($managingEditor); $webMaster = $dom->createElement('webMaster', '[email protected] (webmaster)' ); $channel->appendChild($webMaster); $self = $dom->createElement('atom:link'); $self->setAttribute('href', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); $self->setAttribute('rel', 'self'); $self->setAttribute('type', 'application/rss+xml'); $channel->appendChild($self); // add items foreach( $posts as $post ) { $item = $dom->createElement('item'); $link = $dom->createElement('link', $post['link'] ); // $link->appendChild( $dom->createTextNode( $item['link'] ) ); $item->appendChild( $link ); $title = $dom->createElement('title', $post['title'] ); $item->appendChild( $title ); $description = $dom->createElement('description' ); // put description in cdata to avoid breakage $cdata = $dom->createCDATASection($post['description']); $description->appendChild($cdata); $item->appendChild( $description ); $pubDate = $dom->createElement('pubDate', $post['date'] ); $item->appendChild( $pubDate ); $guid = $dom->createElement('guid', $post['link'] ); $item->appendChild( $guid ); // if enclosure ... if ( isset($post['enclosure']) ) { //<enclosure url="http://www.webmonkey.com/monkeyrock.mpg" length="2471632" type="video/mpeg"/> $enclosure = $dom->createElement('enclosure'); $enclosure->setAttribute('url', $post['enclosure']['url']); $enclosure->setAttribute('length', '1024'); // this is required but doesn't need to be accurate $enclosure->setAttribute('type', $post['enclosure']['type']); // valid mime type $item->appendChild($enclosure); // media rss } $channel->appendChild( $item ); } // cache output if ($config['cache']['output'] == TRUE && is_writable($config['cache']['dir'])) $dom->save($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['output_file']); // send output to browser echo $dom->saveXML(); } /*EOF*/
pjkix/tumblr-dashboard-rss
302df13c4bc490ea7964bc47ebb765f0ad89be23
[changed] cleaned up config vars
diff --git a/README.md b/README.md index 2648b92..8395586 100644 --- a/README.md +++ b/README.md @@ -1,47 +1,47 @@ Tumblr Dashboard RSS ==================== Author: PJ Kix <[email protected]> Version: 1.1.0 Copyright: (cc) 2010 pjkix some rights reserved License: http://creativecommons.org/licenses/by-nc-nd/3.0/ See Also: http://www.tumblr.com/docs/en/api Overview -------- This script uses the tumblr API to read the dashboard xml and then output an RSS feed. Usage ----- Upload the PHP script to a public location on a web server running PHP 5. Either a) edit the php script directly to set authentication or b) copy the config.ini.sample as config.ini and edit the settings. Todo ---- * make it more secure * multi-user friendly * content compression History ------- v1.1.0 (2011-05-17) * support for post types * support enclosure / media rss * support request caching * support output caching -* + v1.0.4 (2010-02-01) * initial release * support for basic rss feed * support for http cache control header * support conditional get \ No newline at end of file diff --git a/tumblr-dashboard-rss.php b/tumblr-dashboard-rss.php index f19ae49..4ee017c 100644 --- a/tumblr-dashboard-rss.php +++ b/tumblr-dashboard-rss.php @@ -1,358 +1,351 @@ <?php /** * Tumblr Dashboard RSS Feed * * features: valid rss, cache-control, conditional get, easy config * requires: curl, dom, simplexml * @package Feeds * @author PJ Kix <[email protected]> * @copyright (cc) 2010 pjkix * @license http://creativecommons.org/licenses/by-nc-nd/3.0/ * @see http://www.tumblr.com/docs/en/api * @version 1.2.0 $Id:$ * @todo post types, make it more secure, multi-user friendly, compression, cacheing */ //* debug ini_set('display_errors', TRUE) ; error_reporting (E_ALL | E_STRICT) ; //*/ /** Authorization info */ -$tumblr['email'] = '[email protected]'; -$tumblr['password'] = 'password'; +$config['tumblr']['email'] = '[email protected]'; +$config['tumblr']['password'] = 'password'; /** other settings*/ -$_DEBUG = TRUE; -$cache_request = TRUE; -$cache_output = TRUE; -$cache_ttl = '300'; // 5m in seconds -$cache_dir = './cache'; // make sure this is writeable for www server -$request_file = 'dashboard.raw.xml'; -$output_file = 'dashboard.rss.xml'; -$img_size = 5; // 0-5 (0 is original or large, 5 is small) -//$title_format = '[%1$s] %4$s (%2$s) - %3$s'; // [type] longname (shortname) - entry -$title_format = '%3$s (%2$s) - %4$s [%1$s]'; // longname (shortname) - entry [type] +$config['DEBUG'] = FALSE; +$config['cache']['request'] = TRUE; +$config['cache']['output'] = TRUE; +$config['cache']['ttl'] = '300'; // 5m in seconds +$config['cache']['dir'] = './cache'; // make sure this is writeable for www server +$config['cache']['request_file'] = 'dashboard.raw.xml'; +$config['cache']['output_file'] = 'dashboard.rss.xml'; +$config['feed']['img_size'] = 5; // 0-5 (0 is original or large, 5 is small) +//$config['feed']['post_format'] = '[%1$s] %4$s (%2$s) - %3$s'; // [type] longname (shortname) - entry +$config['feed']['post_format'] = '%3$s (%2$s) - %4$s [%1$s]'; // longname (shortname) - entry [type] /** read config ... if available */ if ( file_exists('config.ini') ) { $config = parse_ini_file('config.ini', TRUE); - extract($config); } // set GMT/UTC required for proper cache dates & feed validation date_default_timezone_set('GMT'); // and away we go ... -if ($cache_request && check_cache() ) +if ($config['cache']['request'] && check_cache() ) { - $result = file_get_contents($cache_dir . DIRECTORY_SEPARATOR . $request_file); + $result = file_get_contents($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file']); $posts = read_xml($result); output_rss($posts); } else { - fetch_tumblr_dashboard_xml($tumblr['email'], $tumblr['password']); + fetch_tumblr_dashboard_xml($config['tumblr']['email'], $config['tumblr']['password']); } /** Functions ------------------------------------- */ /** * Tumbler Dashboard API Read * * @param string $email tumblr account email address * @param string $password tumblr account password * @return void */ function fetch_tumblr_dashboard_xml($email, $password) { // Prepare POST request $request_data = http_build_query( array( 'email' => $email, 'password' => $password, 'generator' => 'tumblr Dashboard Feed 1.1', 'num' => '50' ) ); // Send the POST request (with cURL) $ch = curl_init('http://www.tumblr.com/api/dashboard'); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_USERAGENT, 'tumblr-dashboard-rss 1.1'); curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Check for success if ($status == 200) { // echo "Success! The output is $result.\n"; // do process/output $posts = read_xml($result); output_rss($posts); // cache xml file ... check last mod & serve static cache_xml($result); } else if ($status == 403) { echo 'Bad email or password'; } else if ($status == 503) { echo 'Rate Limit Exceded or Service Down'; } else { echo "Error: $result\n"; } } /** * write xml to local file * @param type $result * @todo chose a cache method - raw or formatted */ function cache_xml($result) { - if (is_writable('./cache')) + global $config; + if ( is_writable($config['cache']['dir']) ) { - $fp = fopen('./cache/dashboard.raw.xml', 'w'); + $fp = fopen($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file'], 'w'); fwrite($fp, $result); fclose($fp); } else { error_log('ERROR: xml cache not writeable'); return FALSE; } - //TMP - // import to simple xml to clean up - $sxml = new SimpleXMLElement($result); - $dom = new DOMDocument('1.0'); - // convert to dom - $dom_sxe = dom_import_simplexml($sxml); - $dom_sxe = $dom->importNode($dom_sxe, TRUE); - $dom_sxe = $dom->appendChild($dom_sxe); - // format & output - $dom->formatOutput = TRUE; - //echo $dom->saveXML(); - $dom->save('./cache/dashboard.clean.xml'); } /** * check if the cache is fresh * @param type $filename cache file path * @param type $ttl time in seconds * @return type bool true if file is fresh false if stale */ -function check_cache($filename='./cache/dashboard.raw.xml', $ttl=300) +function check_cache() { - // check cache ... + global $config; + $filename = $config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['request_file']; + $ttl = (int) $config['cache']['ttl']; + if (file_exists($filename) && filemtime($filename) > time() - $ttl ) { - $GLOBALS['_DEBUG'] && error_log('[DEBUG] CACHE FOUND! AND NOT EXPIRED! :)'); + $config['DEBUG'] && error_log('[DEBUG] CACHE FOUND! AND NOT EXPIRED! :)'); return TRUE; } else { return FALSE; } } /** * parse tumblr dashboard xml * * @param string $result curl result string * @return array $posts array of posts for rss */ function read_xml($result) { - $format = $GLOBALS['title_format']; - $img_size = $GLOBALS['img_size']; + global $config; + $format = $config['feed']['post_format']; + $img_size = (int)$config['feed']['img_size']; // $xml = simplexml_load_string($result); $xml = new SimpleXMLElement($result); // print_r($xml);die; // create simple array $posts = array(); foreach ($xml->posts->post as $post) { $item = array(); // var_dump($post);die; $item['title'] = str_replace('-', ' ', $post['slug']); // default $item['link'] = $post['url-with-slug']; $item['date'] = date(DATE_RSS, strtotime($post['date']) ); $item['description'] = $post['type']; // handle types [Text, Photo, Quote, Link, Chat, Audio, Video] switch($post['type']) { case 'regular': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'regular-title'} ) ; $item['description'] = $post->{'regular-body'}; break; case 'photo': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = sprintf('<img src="%s"/> %s', $post->{'photo-url'}[$img_size], $post->{'photo-caption'} ); $item['enclosure']['url'] = (string)$post->{'photo-url'}[0]; $item['enclosure']['type'] = 'image/jpg'; // FIXME: best guess ... whish i knew without checking extensions // var_dump($post);die; break; case 'quote': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->source) ; $item['description'] = $post->quote; break; case 'answer': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slgu']) ; $item['description'] = $post->answer; break; case 'link': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->link) ; $item['description'] = $post->link; break; case 'conversation': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'conversation-title'} ) ; $item['description'] = $post->{'conversation'}; break; case 'audio': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], strip_tags($post->{'audio-caption'} ) ) ; $item['description'] = $post->{'audio-player'} . $post->{'audio-caption'}; $item['enclosure']['url'] = $post->{'audio-download'}; $item['enclosure']['type'] = 'audio/mp3'; // FIXME: best guess without looking at extension break; case 'video': $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; $item['description'] = 'Video ... embed goes here ... '; $item['enclosure']['url'] = $post->{'video-download'}; $item['enclosure']['type'] = 'video/mp4'; // FIXME: best guess without looking at extension break; default: $item['description'] = 'unknown post type: ' . $post['type']; break; } // append to array $posts[] = $item; } // var_dump($posts);die; return $posts; } /** * generate rss feed output * * @param array $items post item array * @return void */ function output_rss ($posts, $cache=false, $file=NULL) { + global $config; if (!is_array($posts)) die('no posts ...'); $lastmod = strtotime($posts[0]['date']); // http headers header('Content-type: text/xml'); // set mime ... application/rss+xml header('Cache-Control: max-age=300, must-revalidate'); // cache control 5 mins header('Last-Modified: ' . gmdate('D, j M Y H:i:s T', $lastmod) ); //D, j M Y H:i:s T header('Expires: ' . gmdate('D, j M Y H:i:s T', time() + 300)); // conditional get ... $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === gmdate('D, j M Y H:i:s T', $lastmod) : FALSE; if ( FALSE !== $ifmod ) { - $GLOBALS['_DEBUG'] && error_log('[DEBUG] 304 NOT MODIFIED :)'); + $config['DEBUG'] && error_log('[DEBUG] 304 NOT MODIFIED :)'); header('HTTP/1.0 304 Not Modified'); exit; } // build rss using dom $dom = new DomDocument(); $dom->formatOutput = TRUE; $dom->encoding = 'utf-8'; $rss = $dom->createElement('rss'); $rss->setAttribute('version', '2.0'); $rss->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); // atom for self $rss->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/'); //xmlns:media="http://search.yahoo.com/mrss/" $dom->appendChild($rss); $channel = $dom->createElement('channel'); $rss->appendChild($channel); // set up feed properties $title = $dom->createElement('title', 'My Tumblr Dashboard Feed'); $channel->appendChild($title); $link = $dom->createElement('link', 'http://tumblr.com/dashboard'); $channel->appendChild($link); $description = $dom->createElement('description', 'My tumblr dashboard feed'); $channel->appendChild($description); $language = $dom->createElement('language', 'en-us'); $channel->appendChild($language); $pubDate = $dom->createElement('pubDate', $posts[0]['date'] ); $channel->appendChild($pubDate); $lastBuild = $dom->createElement('lastBuildDate', date(DATE_RSS) ); $channel->appendChild($lastBuild); $docs = $dom->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss' ); $channel->appendChild($docs); $generator = $dom->createElement('generator', 'Tumbler API' ); $channel->appendChild($generator); $managingEditor = $dom->createElement('managingEditor', '[email protected] (editor)' ); $channel->appendChild($managingEditor); $webMaster = $dom->createElement('webMaster', '[email protected] (webmaster)' ); $channel->appendChild($webMaster); $self = $dom->createElement('atom:link'); $self->setAttribute('href', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); $self->setAttribute('rel', 'self'); $self->setAttribute('type', 'application/rss+xml'); $channel->appendChild($self); // add items foreach( $posts as $post ) { $item = $dom->createElement('item'); $link = $dom->createElement('link', $post['link'] ); // $link->appendChild( $dom->createTextNode( $item['link'] ) ); $item->appendChild( $link ); $title = $dom->createElement('title', $post['title'] ); $item->appendChild( $title ); $description = $dom->createElement('description' ); // put description in cdata to avoid breakage $cdata = $dom->createCDATASection($post['description']); $description->appendChild($cdata); $item->appendChild( $description ); $pubDate = $dom->createElement('pubDate', $post['date'] ); $item->appendChild( $pubDate ); $guid = $dom->createElement('guid', $post['link'] ); $item->appendChild( $guid ); // if enclosure ... if ( isset($post['enclosure']) ) { //<enclosure url="http://www.webmonkey.com/monkeyrock.mpg" length="2471632" type="video/mpeg"/> $enclosure = $dom->createElement('enclosure'); $enclosure->setAttribute('url', $post['enclosure']['url']); $enclosure->setAttribute('length', '1024'); // this is required but doesn't need to be accurate $enclosure->setAttribute('type', $post['enclosure']['type']); // valid mime type $item->appendChild($enclosure); // media rss } $channel->appendChild( $item ); } // cache output - if ($GLOBALS['cache_output'] === TRUE && is_writable($GLOBALS['cache_dir'])) - $dom->save($GLOBALS['cache_dir'] . DIRECTORY_SEPARATOR . $GLOBALS['output_file']); + if ($config['cache']['output'] == TRUE && is_writable($config['cache']['dir'])) + $dom->save($config['cache']['dir'] . DIRECTORY_SEPARATOR . $config['cache']['output_file']); // send output to browser echo $dom->saveXML(); } /*EOF*/
pjkix/tumblr-dashboard-rss
3ff1bd6434032761c760d77b8366a4aaf016043c
[added] support for post types [added] support enclosure / media rss [added] support request caching [added] support output caching
diff --git a/.gitignore b/.gitignore index 2fa7ce7..98e289e 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ config.ini +/cache/ \ No newline at end of file diff --git a/.htaccess b/.htaccess index 1230313..1e19b29 100644 --- a/.htaccess +++ b/.htaccess @@ -1,5 +1,7 @@ # Protect files and directories +#<Files ~ "\.(gif|jpe?g|png)$"> +#<FilesMatch "\.(gif|jpe?g|png)$"> <Files ~ "(\.(conf|svn|git|inc|pl|sh|sql|tpl)|Repositories|scripts|updates|_notes|config.ini)$"> order deny,allow deny from all </Files> \ No newline at end of file diff --git a/README b/README.md similarity index 59% rename from README rename to README.md index 5d93c2b..2648b92 100644 --- a/README +++ b/README.md @@ -1,35 +1,47 @@ Tumblr Dashboard RSS ==================== - Author: + Author: PJ Kix <[email protected]> - Version: - 1.0.4 - Copyright: + Version: + 1.1.0 + Copyright: (cc) 2010 pjkix some rights reserved License: http://creativecommons.org/licenses/by-nc-nd/3.0/ See Also: http://www.tumblr.com/docs/en/api Overview -------- This script uses the tumblr API to read the dashboard xml and then output an RSS feed. Usage ----- Upload the PHP script to a public location on a web server running PHP 5. -Either a) edit the php script directly to set authentication +Either a) edit the php script directly to set authentication or b) copy the config.ini.sample as config.ini and edit the settings. Todo ---- -* switch post types -* content embeding / previews * make it more secure * multi-user friendly * content compression -* api request caching +History +------- + +v1.1.0 (2011-05-17) +* support for post types +* support enclosure / media rss +* support request caching +* support output caching +* + +v1.0.4 (2010-02-01) +* initial release +* support for basic rss feed +* support for http cache control header +* support conditional get \ No newline at end of file diff --git a/config.ini.sample b/config.ini.sample index d1e0f18..11ad0cf 100644 --- a/config.ini.sample +++ b/config.ini.sample @@ -1,11 +1,25 @@ ;; Tumblr Dashboard RSS settings -;; note: single quotes might break, but double quotes or no quotes is fine +;; note: single quotes might break, but double quotes or no quotes is fine + +[genral] +_DEBUG = TRUE [tumblr] email = "[email protected]" password = "password" [feed] title = "My tumbler Dashboard Feed" link = http://tumblr.com/dashboard description = "My tumbler dashboard feed" +img_size = 5 ;; 0-5 (0 is original or large, 5 is small) +;; title_format = "[%1$s] %4$s (%2$s) - %3$s" ;; [type] longname (shortname) - entry +title_format = "%3$s (%2$s) - %4$s [%1$s]" ;; longname (shortname) - entry [type] + +[cache] +cache_request = TRUE +cache_output = TRUE +cache_ttl = 300 ;; 5m in seconds +cache_dir = "./cache" ;; make sure this is writeable for www server +request_file = "dashboard.raw.xml" +output_file = "dashboard.rss.xml" diff --git a/tumblr-dashboard-rss.php b/tumblr-dashboard-rss.php index afeee75..f19ae49 100644 --- a/tumblr-dashboard-rss.php +++ b/tumblr-dashboard-rss.php @@ -1,197 +1,358 @@ <?php /** * Tumblr Dashboard RSS Feed - * + * * features: valid rss, cache-control, conditional get, easy config * requires: curl, dom, simplexml * @package Feeds * @author PJ Kix <[email protected]> * @copyright (cc) 2010 pjkix * @license http://creativecommons.org/licenses/by-nc-nd/3.0/ * @see http://www.tumblr.com/docs/en/api - * @version 1.0.4 $Id:$ - * @todo post types, make it more secure, multi-user friendly, compression + * @version 1.2.0 $Id:$ + * @todo post types, make it more secure, multi-user friendly, compression, cacheing */ //* debug -ini_set('display_errors', true) ; +ini_set('display_errors', TRUE) ; error_reporting (E_ALL | E_STRICT) ; //*/ /** Authorization info */ -$tumblr_email = '[email protected]'; -$tumblr_password = 'password'; +$tumblr['email'] = '[email protected]'; +$tumblr['password'] = 'password'; + +/** other settings*/ +$_DEBUG = TRUE; +$cache_request = TRUE; +$cache_output = TRUE; +$cache_ttl = '300'; // 5m in seconds +$cache_dir = './cache'; // make sure this is writeable for www server +$request_file = 'dashboard.raw.xml'; +$output_file = 'dashboard.rss.xml'; +$img_size = 5; // 0-5 (0 is original or large, 5 is small) +//$title_format = '[%1$s] %4$s (%2$s) - %3$s'; // [type] longname (shortname) - entry +$title_format = '%3$s (%2$s) - %4$s [%1$s]'; // longname (shortname) - entry [type] /** read config ... if available */ if ( file_exists('config.ini') ) { - $config = parse_ini_file('config.ini', true); - $tumblr_email = $config['tumblr']['email']; - $tumblr_password = $config['tumblr']['password']; + $config = parse_ini_file('config.ini', TRUE); + extract($config); } - -// default to GMT for dates +// set GMT/UTC required for proper cache dates & feed validation date_default_timezone_set('GMT'); -fetch_tumblr_dashboard_xml($tumblr_email, $tumblr_password); +// and away we go ... +if ($cache_request && check_cache() ) +{ + $result = file_get_contents($cache_dir . DIRECTORY_SEPARATOR . $request_file); + $posts = read_xml($result); + output_rss($posts); +} +else +{ + fetch_tumblr_dashboard_xml($tumblr['email'], $tumblr['password']); +} + /** Functions ------------------------------------- */ /** * Tumbler Dashboard API Read * * @param string $email tumblr account email address * @param string $password tumblr account password * @return void */ -function fetch_tumblr_dashboard_xml($email, $password) { +function fetch_tumblr_dashboard_xml($email, $password) +{ // Prepare POST request $request_data = http_build_query( array( 'email' => $email, 'password' => $password, - 'generator' => 'tumblr Dashboard Feed 1.0', + 'generator' => 'tumblr Dashboard Feed 1.1', 'num' => '50' ) ); // Send the POST request (with cURL) $ch = curl_init('http://www.tumblr.com/api/dashboard'); - curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POST, TRUE); + curl_setopt($ch, CURLOPT_USERAGENT, 'tumblr-dashboard-rss 1.1'); curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Check for success if ($status == 200) { // echo "Success! The output is $result.\n"; + // do process/output $posts = read_xml($result); output_rss($posts); // cache xml file ... check last mod & serve static + cache_xml($result); } else if ($status == 403) { echo 'Bad email or password'; } else if ($status == 503) { echo 'Rate Limit Exceded or Service Down'; } else { echo "Error: $result\n"; } } +/** + * write xml to local file + * @param type $result + * @todo chose a cache method - raw or formatted + */ +function cache_xml($result) +{ + if (is_writable('./cache')) + { + $fp = fopen('./cache/dashboard.raw.xml', 'w'); + fwrite($fp, $result); + fclose($fp); + } + else + { + error_log('ERROR: xml cache not writeable'); + return FALSE; + } + //TMP + // import to simple xml to clean up + $sxml = new SimpleXMLElement($result); + $dom = new DOMDocument('1.0'); + // convert to dom + $dom_sxe = dom_import_simplexml($sxml); + $dom_sxe = $dom->importNode($dom_sxe, TRUE); + $dom_sxe = $dom->appendChild($dom_sxe); + // format & output + $dom->formatOutput = TRUE; + //echo $dom->saveXML(); + $dom->save('./cache/dashboard.clean.xml'); + +} + +/** + * check if the cache is fresh + * @param type $filename cache file path + * @param type $ttl time in seconds + * @return type bool true if file is fresh false if stale + */ +function check_cache($filename='./cache/dashboard.raw.xml', $ttl=300) +{ + // check cache ... + if (file_exists($filename) && filemtime($filename) > time() - $ttl ) + { + $GLOBALS['_DEBUG'] && error_log('[DEBUG] CACHE FOUND! AND NOT EXPIRED! :)'); + return TRUE; + } + else + { + return FALSE; + } + +} + /** * parse tumblr dashboard xml * * @param string $result curl result string * @return array $posts array of posts for rss */ function read_xml($result) { + $format = $GLOBALS['title_format']; + $img_size = $GLOBALS['img_size']; + // $xml = simplexml_load_string($result); $xml = new SimpleXMLElement($result); - // var_dump($xml);die; +// print_r($xml);die; + + // create simple array $posts = array(); - $i = 0; foreach ($xml->posts->post as $post) { - // var_dump($post); - $posts[$i]['title'] = $post['slug']; // wish there was a real title - $posts[$i]['description'] = $post['type']; // maybe do somehting intelligent with type - $posts[$i]['link'] = $post['url-with-slug']; - $posts[$i]['date'] = date(DATE_RSS, strtotime($post['date']) ); - $i++; + $item = array(); + +// var_dump($post);die; + $item['title'] = str_replace('-', ' ', $post['slug']); // default + $item['link'] = $post['url-with-slug']; + $item['date'] = date(DATE_RSS, strtotime($post['date']) ); + $item['description'] = $post['type']; + + // handle types [Text, Photo, Quote, Link, Chat, Audio, Video] + switch($post['type']) + { + case 'regular': + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'regular-title'} ) ; + $item['description'] = $post->{'regular-body'}; + break; + + case 'photo': + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; + $item['description'] = sprintf('<img src="%s"/> %s', $post->{'photo-url'}[$img_size], $post->{'photo-caption'} ); + $item['enclosure']['url'] = (string)$post->{'photo-url'}[0]; + $item['enclosure']['type'] = 'image/jpg'; // FIXME: best guess ... whish i knew without checking extensions +// var_dump($post);die; + break; + + case 'quote': + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->source) ; + $item['description'] = $post->quote; + break; + + case 'answer': + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slgu']) ; + $item['description'] = $post->answer; + break; + + case 'link': + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->link) ; + $item['description'] = $post->link; + break; + + case 'conversation': + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post->{'conversation-title'} ) ; + $item['description'] = $post->{'conversation'}; + break; + + case 'audio': + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], strip_tags($post->{'audio-caption'} ) ) ; + $item['description'] = $post->{'audio-player'} . $post->{'audio-caption'}; + $item['enclosure']['url'] = $post->{'audio-download'}; + $item['enclosure']['type'] = 'audio/mp3'; // FIXME: best guess without looking at extension + break; + + case 'video': + $item['title'] = sprintf($format, $post['type'], $post['tumblelog'], $post->tumblelog['title'], $post['slug']) ; + $item['description'] = 'Video ... embed goes here ... '; + $item['enclosure']['url'] = $post->{'video-download'}; + $item['enclosure']['type'] = 'video/mp4'; // FIXME: best guess without looking at extension + break; + + default: + $item['description'] = 'unknown post type: ' . $post['type']; + break; + } + // append to array + $posts[] = $item; } - // var_dump($posts); +// var_dump($posts);die; return $posts; } - /** * generate rss feed output * * @param array $items post item array * @return void */ -function output_rss ($posts) +function output_rss ($posts, $cache=false, $file=NULL) { if (!is_array($posts)) die('no posts ...'); $lastmod = strtotime($posts[0]['date']); - + // http headers header('Content-type: text/xml'); // set mime ... application/rss+xml header('Cache-Control: max-age=300, must-revalidate'); // cache control 5 mins header('Last-Modified: ' . gmdate('D, j M Y H:i:s T', $lastmod) ); //D, j M Y H:i:s T header('Expires: ' . gmdate('D, j M Y H:i:s T', time() + 300)); - // conditional get ... - $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === gmdate('D, j M Y H:i:s T', $lastmod) : false; - if ( false !== $ifmod ) { - header('HTTP/1.0 304 Not Modified'); - exit; + // conditional get ... + $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === gmdate('D, j M Y H:i:s T', $lastmod) : FALSE; + if ( FALSE !== $ifmod ) { + $GLOBALS['_DEBUG'] && error_log('[DEBUG] 304 NOT MODIFIED :)'); + header('HTTP/1.0 304 Not Modified'); + exit; } // build rss using dom $dom = new DomDocument(); - $dom->formatOutput = true; + $dom->formatOutput = TRUE; $dom->encoding = 'utf-8'; $rss = $dom->createElement('rss'); $rss->setAttribute('version', '2.0'); - $rss->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); + $rss->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); // atom for self + $rss->setAttribute('xmlns:media', 'http://search.yahoo.com/mrss/'); //xmlns:media="http://search.yahoo.com/mrss/" $dom->appendChild($rss); $channel = $dom->createElement('channel'); $rss->appendChild($channel); // set up feed properties $title = $dom->createElement('title', 'My Tumblr Dashboard Feed'); $channel->appendChild($title); $link = $dom->createElement('link', 'http://tumblr.com/dashboard'); $channel->appendChild($link); $description = $dom->createElement('description', 'My tumblr dashboard feed'); $channel->appendChild($description); $language = $dom->createElement('language', 'en-us'); $channel->appendChild($language); $pubDate = $dom->createElement('pubDate', $posts[0]['date'] ); $channel->appendChild($pubDate); $lastBuild = $dom->createElement('lastBuildDate', date(DATE_RSS) ); $channel->appendChild($lastBuild); $docs = $dom->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss' ); $channel->appendChild($docs); $generator = $dom->createElement('generator', 'Tumbler API' ); $channel->appendChild($generator); $managingEditor = $dom->createElement('managingEditor', '[email protected] (editor)' ); $channel->appendChild($managingEditor); $webMaster = $dom->createElement('webMaster', '[email protected] (webmaster)' ); $channel->appendChild($webMaster); $self = $dom->createElement('atom:link'); $self->setAttribute('href', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); $self->setAttribute('rel', 'self'); $self->setAttribute('type', 'application/rss+xml'); $channel->appendChild($self); // add items foreach( $posts as $post ) { - $item = $dom->createElement( "item" ); + $item = $dom->createElement('item'); - $link = $dom->createElement( 'link', $post['link'] ); + $link = $dom->createElement('link', $post['link'] ); // $link->appendChild( $dom->createTextNode( $item['link'] ) ); $item->appendChild( $link ); - $title = $dom->createElement( "title" , $post['title'] ); + $title = $dom->createElement('title', $post['title'] ); $item->appendChild( $title ); - $description = $dom->createElement( "description", $post['description'] ); + $description = $dom->createElement('description' ); + // put description in cdata to avoid breakage + $cdata = $dom->createCDATASection($post['description']); + $description->appendChild($cdata); $item->appendChild( $description ); - $pubDate = $dom->createElement( "pubDate", $post['date'] ); + $pubDate = $dom->createElement('pubDate', $post['date'] ); $item->appendChild( $pubDate ); - $guid = $dom->createElement( "guid", $post['link'] ); + $guid = $dom->createElement('guid', $post['link'] ); $item->appendChild( $guid ); + // if enclosure ... + if ( isset($post['enclosure']) ) + { + //<enclosure url="http://www.webmonkey.com/monkeyrock.mpg" length="2471632" type="video/mpeg"/> + $enclosure = $dom->createElement('enclosure'); + $enclosure->setAttribute('url', $post['enclosure']['url']); + $enclosure->setAttribute('length', '1024'); // this is required but doesn't need to be accurate + $enclosure->setAttribute('type', $post['enclosure']['type']); // valid mime type + $item->appendChild($enclosure); + + // media rss + } + $channel->appendChild( $item ); } + // cache output + if ($GLOBALS['cache_output'] === TRUE && is_writable($GLOBALS['cache_dir'])) + $dom->save($GLOBALS['cache_dir'] . DIRECTORY_SEPARATOR . $GLOBALS['output_file']); + // send output to browser echo $dom->saveXML(); } - -?> +/*EOF*/
pjkix/tumblr-dashboard-rss
045bb8bcfbe6839993efc5f5724a1ff1b2bf088d
tweak cache, date, add .htaccess rules
diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..1230313 --- /dev/null +++ b/.htaccess @@ -0,0 +1,5 @@ +# Protect files and directories +<Files ~ "(\.(conf|svn|git|inc|pl|sh|sql|tpl)|Repositories|scripts|updates|_notes|config.ini)$"> + order deny,allow + deny from all +</Files> \ No newline at end of file diff --git a/tumblr-dashboard-rss.php b/tumblr-dashboard-rss.php index 45973d1..afeee75 100644 --- a/tumblr-dashboard-rss.php +++ b/tumblr-dashboard-rss.php @@ -1,197 +1,197 @@ <?php /** * Tumblr Dashboard RSS Feed * * features: valid rss, cache-control, conditional get, easy config * requires: curl, dom, simplexml * @package Feeds * @author PJ Kix <[email protected]> * @copyright (cc) 2010 pjkix * @license http://creativecommons.org/licenses/by-nc-nd/3.0/ * @see http://www.tumblr.com/docs/en/api * @version 1.0.4 $Id:$ * @todo post types, make it more secure, multi-user friendly, compression */ //* debug ini_set('display_errors', true) ; error_reporting (E_ALL | E_STRICT) ; //*/ /** Authorization info */ $tumblr_email = '[email protected]'; $tumblr_password = 'password'; /** read config ... if available */ if ( file_exists('config.ini') ) { $config = parse_ini_file('config.ini', true); $tumblr_email = $config['tumblr']['email']; $tumblr_password = $config['tumblr']['password']; } // default to GMT for dates -// date_default_timezone_set('GMT'); +date_default_timezone_set('GMT'); fetch_tumblr_dashboard_xml($tumblr_email, $tumblr_password); /** Functions ------------------------------------- */ /** * Tumbler Dashboard API Read * * @param string $email tumblr account email address * @param string $password tumblr account password * @return void */ function fetch_tumblr_dashboard_xml($email, $password) { // Prepare POST request $request_data = http_build_query( array( 'email' => $email, 'password' => $password, 'generator' => 'tumblr Dashboard Feed 1.0', 'num' => '50' ) ); // Send the POST request (with cURL) $ch = curl_init('http://www.tumblr.com/api/dashboard'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Check for success if ($status == 200) { // echo "Success! The output is $result.\n"; $posts = read_xml($result); output_rss($posts); // cache xml file ... check last mod & serve static } else if ($status == 403) { echo 'Bad email or password'; } else if ($status == 503) { echo 'Rate Limit Exceded or Service Down'; } else { echo "Error: $result\n"; } } /** * parse tumblr dashboard xml * * @param string $result curl result string * @return array $posts array of posts for rss */ function read_xml($result) { // $xml = simplexml_load_string($result); $xml = new SimpleXMLElement($result); // var_dump($xml);die; $posts = array(); $i = 0; foreach ($xml->posts->post as $post) { // var_dump($post); $posts[$i]['title'] = $post['slug']; // wish there was a real title $posts[$i]['description'] = $post['type']; // maybe do somehting intelligent with type $posts[$i]['link'] = $post['url-with-slug']; $posts[$i]['date'] = date(DATE_RSS, strtotime($post['date']) ); $i++; } // var_dump($posts); return $posts; } /** * generate rss feed output * * @param array $items post item array * @return void */ function output_rss ($posts) { if (!is_array($posts)) die('no posts ...'); $lastmod = strtotime($posts[0]['date']); // http headers header('Content-type: text/xml'); // set mime ... application/rss+xml header('Cache-Control: max-age=300, must-revalidate'); // cache control 5 mins header('Last-Modified: ' . gmdate('D, j M Y H:i:s T', $lastmod) ); //D, j M Y H:i:s T header('Expires: ' . gmdate('D, j M Y H:i:s T', time() + 300)); // conditional get ... $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === gmdate('D, j M Y H:i:s T', $lastmod) : false; if ( false !== $ifmod ) { header('HTTP/1.0 304 Not Modified'); exit; } // build rss using dom $dom = new DomDocument(); $dom->formatOutput = true; $dom->encoding = 'utf-8'; $rss = $dom->createElement('rss'); $rss->setAttribute('version', '2.0'); $rss->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); $dom->appendChild($rss); $channel = $dom->createElement('channel'); $rss->appendChild($channel); // set up feed properties $title = $dom->createElement('title', 'My Tumblr Dashboard Feed'); $channel->appendChild($title); $link = $dom->createElement('link', 'http://tumblr.com/dashboard'); $channel->appendChild($link); $description = $dom->createElement('description', 'My tumblr dashboard feed'); $channel->appendChild($description); $language = $dom->createElement('language', 'en-us'); $channel->appendChild($language); $pubDate = $dom->createElement('pubDate', $posts[0]['date'] ); $channel->appendChild($pubDate); $lastBuild = $dom->createElement('lastBuildDate', date(DATE_RSS) ); $channel->appendChild($lastBuild); $docs = $dom->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss' ); $channel->appendChild($docs); $generator = $dom->createElement('generator', 'Tumbler API' ); $channel->appendChild($generator); $managingEditor = $dom->createElement('managingEditor', '[email protected] (editor)' ); $channel->appendChild($managingEditor); $webMaster = $dom->createElement('webMaster', '[email protected] (webmaster)' ); $channel->appendChild($webMaster); $self = $dom->createElement('atom:link'); $self->setAttribute('href', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); $self->setAttribute('rel', 'self'); $self->setAttribute('type', 'application/rss+xml'); $channel->appendChild($self); // add items foreach( $posts as $post ) { $item = $dom->createElement( "item" ); $link = $dom->createElement( 'link', $post['link'] ); // $link->appendChild( $dom->createTextNode( $item['link'] ) ); $item->appendChild( $link ); $title = $dom->createElement( "title" , $post['title'] ); $item->appendChild( $title ); $description = $dom->createElement( "description", $post['description'] ); $item->appendChild( $description ); $pubDate = $dom->createElement( "pubDate", $post['date'] ); $item->appendChild( $pubDate ); $guid = $dom->createElement( "guid", $post['link'] ); $item->appendChild( $guid ); $channel->appendChild( $item ); } echo $dom->saveXML(); } ?>
pjkix/tumblr-dashboard-rss
4e810248a95a2d7f608b5c1585fd90531795052d
tweak cache settings
diff --git a/tumblr-dashboard-rss.php b/tumblr-dashboard-rss.php index 5f6763c..45973d1 100644 --- a/tumblr-dashboard-rss.php +++ b/tumblr-dashboard-rss.php @@ -1,187 +1,197 @@ <?php /** * Tumblr Dashboard RSS Feed * * features: valid rss, cache-control, conditional get, easy config * requires: curl, dom, simplexml * @package Feeds * @author PJ Kix <[email protected]> * @copyright (cc) 2010 pjkix * @license http://creativecommons.org/licenses/by-nc-nd/3.0/ * @see http://www.tumblr.com/docs/en/api * @version 1.0.4 $Id:$ * @todo post types, make it more secure, multi-user friendly, compression */ +//* debug +ini_set('display_errors', true) ; +error_reporting (E_ALL | E_STRICT) ; +//*/ + /** Authorization info */ $tumblr_email = '[email protected]'; $tumblr_password = 'password'; /** read config ... if available */ if ( file_exists('config.ini') ) { $config = parse_ini_file('config.ini', true); $tumblr_email = $config['tumblr']['email']; $tumblr_password = $config['tumblr']['password']; } +// default to GMT for dates +// date_default_timezone_set('GMT'); + fetch_tumblr_dashboard_xml($tumblr_email, $tumblr_password); /** Functions ------------------------------------- */ /** * Tumbler Dashboard API Read * * @param string $email tumblr account email address * @param string $password tumblr account password * @return void */ function fetch_tumblr_dashboard_xml($email, $password) { // Prepare POST request $request_data = http_build_query( array( 'email' => $email, 'password' => $password, 'generator' => 'tumblr Dashboard Feed 1.0', 'num' => '50' ) ); // Send the POST request (with cURL) $ch = curl_init('http://www.tumblr.com/api/dashboard'); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($ch); $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); // Check for success if ($status == 200) { // echo "Success! The output is $result.\n"; $posts = read_xml($result); output_rss($posts); // cache xml file ... check last mod & serve static } else if ($status == 403) { echo 'Bad email or password'; } else if ($status == 503) { echo 'Rate Limit Exceded or Service Down'; } else { echo "Error: $result\n"; } } /** * parse tumblr dashboard xml * * @param string $result curl result string * @return array $posts array of posts for rss */ function read_xml($result) { // $xml = simplexml_load_string($result); $xml = new SimpleXMLElement($result); // var_dump($xml);die; $posts = array(); $i = 0; foreach ($xml->posts->post as $post) { // var_dump($post); $posts[$i]['title'] = $post['slug']; // wish there was a real title $posts[$i]['description'] = $post['type']; // maybe do somehting intelligent with type $posts[$i]['link'] = $post['url-with-slug']; $posts[$i]['date'] = date(DATE_RSS, strtotime($post['date']) ); $i++; } // var_dump($posts); return $posts; } /** * generate rss feed output * * @param array $items post item array * @return void */ function output_rss ($posts) { if (!is_array($posts)) die('no posts ...'); $lastmod = strtotime($posts[0]['date']); + // http headers header('Content-type: text/xml'); // set mime ... application/rss+xml - header('Cache-Control: max-age=3600, must-revalidate'); // cache control - header('Last-Modified: ' . date('r', $lastmod) ); - header('Expires: ' . date('r', $lastmod + 3600)); + header('Cache-Control: max-age=300, must-revalidate'); // cache control 5 mins + header('Last-Modified: ' . gmdate('D, j M Y H:i:s T', $lastmod) ); //D, j M Y H:i:s T + header('Expires: ' . gmdate('D, j M Y H:i:s T', time() + 300)); // conditional get ... - $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === date('r', $lastmod) : false; + $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === gmdate('D, j M Y H:i:s T', $lastmod) : false; if ( false !== $ifmod ) { header('HTTP/1.0 304 Not Modified'); exit; } + // build rss using dom $dom = new DomDocument(); $dom->formatOutput = true; $dom->encoding = 'utf-8'; $rss = $dom->createElement('rss'); $rss->setAttribute('version', '2.0'); $rss->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); $dom->appendChild($rss); $channel = $dom->createElement('channel'); $rss->appendChild($channel); // set up feed properties $title = $dom->createElement('title', 'My Tumblr Dashboard Feed'); $channel->appendChild($title); $link = $dom->createElement('link', 'http://tumblr.com/dashboard'); $channel->appendChild($link); $description = $dom->createElement('description', 'My tumblr dashboard feed'); $channel->appendChild($description); $language = $dom->createElement('language', 'en-us'); $channel->appendChild($language); $pubDate = $dom->createElement('pubDate', $posts[0]['date'] ); $channel->appendChild($pubDate); $lastBuild = $dom->createElement('lastBuildDate', date(DATE_RSS) ); $channel->appendChild($lastBuild); $docs = $dom->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss' ); $channel->appendChild($docs); $generator = $dom->createElement('generator', 'Tumbler API' ); $channel->appendChild($generator); $managingEditor = $dom->createElement('managingEditor', '[email protected] (editor)' ); $channel->appendChild($managingEditor); $webMaster = $dom->createElement('webMaster', '[email protected] (webmaster)' ); $channel->appendChild($webMaster); $self = $dom->createElement('atom:link'); $self->setAttribute('href', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); $self->setAttribute('rel', 'self'); $self->setAttribute('type', 'application/rss+xml'); $channel->appendChild($self); // add items foreach( $posts as $post ) { $item = $dom->createElement( "item" ); $link = $dom->createElement( 'link', $post['link'] ); // $link->appendChild( $dom->createTextNode( $item['link'] ) ); $item->appendChild( $link ); $title = $dom->createElement( "title" , $post['title'] ); $item->appendChild( $title ); $description = $dom->createElement( "description", $post['description'] ); $item->appendChild( $description ); $pubDate = $dom->createElement( "pubDate", $post['date'] ); $item->appendChild( $pubDate ); $guid = $dom->createElement( "guid", $post['link'] ); $item->appendChild( $guid ); $channel->appendChild( $item ); } echo $dom->saveXML(); } ?>
pjkix/tumblr-dashboard-rss
5552eec8a965cb257acc09aa039dcad525a56d12
init project
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2fa7ce7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +config.ini diff --git a/README b/README new file mode 100644 index 0000000..80fb670 --- /dev/null +++ b/README @@ -0,0 +1,33 @@ +Tumblr Dashboard RSS +==================== + + Author: + PJ Kix <[email protected]> + Version: + 1.0.3 + Copyright: + (cc) 2010 pjkix + License: + http://creativecommons.org/licenses/by-nc-nd/3.0/ + See Also: + http://www.tumblr.com/docs/en/api + +Overview +-------- + +This PHP script uses the tumblr API to read the dashboard xml and then output an RSS feed. + +Usage +----- + +upload the script to a public location on a web server running php. +either edit the php script directly to set authentication or edit the config.ini + +Todo +---- + +* make it more secure +* multi-user friendly +* content compression +* api request caching + diff --git a/config.ini.sample b/config.ini.sample new file mode 100644 index 0000000..8240a88 --- /dev/null +++ b/config.ini.sample @@ -0,0 +1,11 @@ +;; Tumblr Dashboard RSS settings +;; note: single quotes might break, but double quotes or no quotes is fine + +[tumblr] +email = "[email protected]" +password = "password" + +[feed] +title = "My tumbler feed" +link = http://example.com +description = "my tumbler dashboard feed" diff --git a/tumblr-dashboard-rss.php b/tumblr-dashboard-rss.php new file mode 100644 index 0000000..6bf26df --- /dev/null +++ b/tumblr-dashboard-rss.php @@ -0,0 +1,184 @@ +<?php +/** + * Tumblr Dashboard RSS Feed + * + * features: valid rss, cache-control, conditional get, easy config + * requires: curl, dom, simplexml + * @package Feeds + * @author PJ Kix <[email protected]> + * @copyright (cc) 2010 pjkix + * @license http://creativecommons.org/licenses/by-nc-nd/3.0/ + * @see http://www.tumblr.com/docs/en/api + * @version 1.0.3 $Id:$ + * @todo make it more secure, multi-user friendly, compression + */ + +/** Authorization info */ +$tumblr_email = '[email protected]'; +$tumblr_password = 'password'; + +/** read config ... if available */ +if ( file_exists('config.ini') ) { + $config = parse_ini_file('config.ini', true); + $tumblr_email = $config['tumblr']['email']; + $tumblr_password = $config['tumblr']['password']; +} + +fetch_tumblr_dashboard_xml($tumblr_email, $tumblr_password); + +/** Functions + ------------------------------------- */ + +/** + * Tumbler Dashboard API Read + * + * @param string $email tumblr account email address + * @param string $password tumblr account password + * @return void + */ +function fetch_tumblr_dashboard_xml($email, $password) { + // Prepare POST request + $request_data = http_build_query( + array( + 'email' => $email, + 'password' => $password, + 'generator' => 'API example' + ) + ); + + // Send the POST request (with cURL) + $ch = curl_init('http://www.tumblr.com/api/dashboard'); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $request_data); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + $result = curl_exec($ch); + $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + + // Check for success + if ($status == 200) { + // echo "Success! The output is $result.\n"; + $posts = read_xml($result); + output_rss($posts); + // cache xml file ... check last mod & serve static + } else if ($status == 403) { + echo 'Bad email or password'; + } else { + echo "Error: $result\n"; + } +} + +/** + * parse tumblr dashboard xml + * + * @param string $result curl result string + * @return array $posts array of posts for rss + */ +function read_xml($result) +{ + // $xml = simplexml_load_string($result); + $xml = new SimpleXMLElement($result); + // var_dump($xml);die; + $posts = array(); + $i = 0; + foreach ($xml->posts->post as $post) { + // var_dump($post); + $posts[$i]['title'] = $post['slug']; + $posts[$i]['description'] = $post['type']; // maybe do somehting intelligent with type + $posts[$i]['link'] = $post['url-with-slug']; // wish there was a real title + $posts[$i]['date'] = date(DATE_RSS, strtotime($post['date']) ); + $i++; + } + // var_dump($posts); + return $posts; +} + + +/** + * generate rss feed output + * + * @param array $items post item array + * @return void + */ +function output_rss ($posts) +{ + if (!is_array($posts)) die('no posts ...'); + $lastmod = strtotime($posts[0]['date']); + + header('Content-type: text/xml'); // set mime ... application/rss+xml + header('Cache-Control: max-age=3600, must-revalidate'); // cache control + header('Last-Modified: ' . date('r', $lastmod) ); + header('Expires: ' . date('r', $lastmod + 3600)); + + // conditional get ... + $ifmod = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] === date('r', $lastmod) : false; + if ( false !== $ifmod ) { + header('HTTP/1.0 304 Not Modified'); + exit; + } + + $dom = new DomDocument(); + $dom->formatOutput = true; + $dom->encoding = 'utf-8'; + + $rss = $dom->createElement('rss'); + $rss->setAttribute('version', '2.0'); + $rss->setAttribute('xmlns:atom', 'http://www.w3.org/2005/Atom'); + $dom->appendChild($rss); + + $channel = $dom->createElement('channel'); + $rss->appendChild($channel); + + // set up feed properties + $title = $dom->createElement('title', 'Feed Title'); + $channel->appendChild($title); + $link = $dom->createElement('link', 'http://example.com'); + $channel->appendChild($link); + $description = $dom->createElement('description', 'Feed description'); + $channel->appendChild($description); + $language = $dom->createElement('language', 'en-us'); + $channel->appendChild($language); + $pubDate = $dom->createElement('pubDate', $posts[0]['date'] ); + $channel->appendChild($pubDate); + $lastBuild = $dom->createElement('lastBuildDate', date(DATE_RSS) ); + $channel->appendChild($lastBuild); + $docs = $dom->createElement('docs', 'http://blogs.law.harvard.edu/tech/rss' ); + $channel->appendChild($docs); + $generator = $dom->createElement('generator', 'Tumbler API' ); + $channel->appendChild($generator); + $managingEditor = $dom->createElement('managingEditor', '[email protected] (editor)' ); + $channel->appendChild($managingEditor); + $webMaster = $dom->createElement('webMaster', '[email protected] (webmaster)' ); + $channel->appendChild($webMaster); + $self = $dom->createElement('atom:link'); + $self->setAttribute('href', 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']); + $self->setAttribute('rel', 'self'); + $self->setAttribute('type', 'application/rss+xml'); + $channel->appendChild($self); + + // add items + foreach( $posts as $post ) + { + $item = $dom->createElement( "item" ); + + $link = $dom->createElement( 'link', $post['link'] ); + // $link->appendChild( $dom->createTextNode( $item['link'] ) ); + $item->appendChild( $link ); + $title = $dom->createElement( "title" , $post['title'] ); + $item->appendChild( $title ); + $description = $dom->createElement( "description", $post['description'] ); + $item->appendChild( $description ); + $pubDate = $dom->createElement( "pubDate", $post['date'] ); + $item->appendChild( $pubDate ); + $guid = $dom->createElement( "guid", $post['link'] ); + $item->appendChild( $guid ); + + $channel->appendChild( $item ); + } + + echo $dom->saveXML(); + +} + + +?>
wolframkriesing/doh2
889d9cd4334d39d49254522ba16448c0f8fe7316
Added license file, i know way too late ...
diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..160f4fc --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2009-2011 uxebu Consulting Ltd. & Co. KG (Wolfram Kriesing) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/TODO.txt b/TODO.txt index 7d4b102..d50401c 100644 --- a/TODO.txt +++ b/TODO.txt @@ -1,5 +1,11 @@ TODO * what shall happen when tearDown() throws an error? currently the error is caught, so the suite continues to execute, but shall this throw an error, make the test fail, be silent? being silent means that the - following tests may fail because the test couldnt clean up ... \ No newline at end of file + following tests may fail because the test couldnt clean up ... +* allow success() take multiple parameters, just like console.log() + in doh.js line 99 we would have to do + d.test.result = Array.prototype.slice.apply(arguments); + instead of + d.test.result = msg; +
wolframkriesing/doh2
6523b6b2772492747694cc10021f9a2cefcd0927
+ catch errors in setUp() and tearDown()
diff --git a/TODO.txt b/TODO.txt new file mode 100644 index 0000000..7d4b102 --- /dev/null +++ b/TODO.txt @@ -0,0 +1,5 @@ +TODO +* what shall happen when tearDown() throws an error? + currently the error is caught, so the suite continues to execute, but shall this throw + an error, make the test fail, be silent? being silent means that the + following tests may fail because the test couldnt clean up ... \ No newline at end of file diff --git a/doh.js b/doh.js index a0e0aa8..a9db224 100644 --- a/doh.js +++ b/doh.js @@ -1,231 +1,242 @@ doh = { // This is a temporary structure which points to the current data. _current:{ group:null, groupIndex:-1, test:null, testIndex:-1 }, // A helper property, which stores a reference to a test group by name. _groupsByName:{}, // Statistical data. _numTests:0, // The total number of tests. _numTestsExecuted:0, // Number of tests already executed. // Stats about the test results. _numErrors:0, _numFailures:0, // _isPaused:false, _defaultTimeout:1000, _testInFlight:false, // The groups must be an array, since an object does not necessarily maintain // it's order, but tests should be executed in the order as added. // This might become even more important when test dependencies will be added, // which means only execute test2 if test1 succeeded. _groups:[], _additionalGroupProperties:{ numTestsExecuted:0, numFailures:0, numErrors:0 }, pause:function(){ this._isPaused = true; }, register:function(groupName, tests){ // summary: Register the given tests to the group with the given name. // description: The tests are internally stored in "_groups", an array // which contains all the tests per group. The new tests are added // to the group with the given name, if it didnt exist yet it is created. var group = null; if (this._groupsByName[groupName]){ group = this._groupsByName[groupName]; } else { this._groups.push({name:groupName, tests:[]}); group = this._groupsByName[groupName] = this._groups[this._groups.length-1]; } for (var i=0, l=tests.length, t; i<l; i++){ group.tests.push(tests[i]); } this._numTests += tests.length; }, run:function(){ if (this._current.group===null){ this.ui.started(); } this._isPaused = false; if (this._testInFlight){ return; } this._runNextTest(); }, _getAssertWrapper:function(d){ // summary: This returns an object which provides all the assert methods, and wraps a Deferred instance. // description: Why that? The interface for doh tests should be the same // for synchronous and asynchronous tests. The old version required // you to "know" and "think" when writing asynch tests, and the // assert methods had not been available directly when writing // asynchronous tests, you had to use doh.callback/errback. // This allows to ONLY use assert*() methods. See the selftests // for examples. var myT = new function(){ this._assertClosure = function(method, args){ // If the Deferred instance is already "done", means callback or errback // had already been called don't do it again. // This might be the case when e.g. the test timed out. if (d.fired > -1){ console.log('FIXXXXXME multiple asserts or timeout ... d.fired = ', d.fired, "GROUP and TEST: '", d.test.group.name, "' " , d.test.name); return; } try{ var ret = doh.assert[method].apply(doh, args); d.callback(ret || true); }catch(e){ d.errback(e); } }; this.success = function(msg){ // This function can be used to directly make a test succeed. //TODO write selftest for it!!!!!!!!! d.test.result = msg; d.callback(msg); }; this.failure = function(msg){ //TODO write selftest for it!!!!!!!!! d.errback(new doh.assert.Failure(msg)); }; var that = this; for (var methodName in doh.assert){ if (methodName.indexOf("assert")===0){ this[methodName] = (function(methodName){return function(){ // Make sure the current callstack is worked off before // returning from any assert() method, we do this by // setTimeout(). The bug was that assert() didn't make the // test execute the return statement (if one was in there) // before the test ended, this fixes it. setTimeout(doh.util.hitch(that, "_assertClosure", methodName, arguments), 1); }})(methodName); } } }; return myT; }, _selectNextTest:function(){ var c = this._current; // Is there a test left in this group? if (c.group && c.testIndex < c.group.tests.length-1){ c.testIndex++; } else { // First test in the next group, if there is another group. if (c.groupIndex < this._groups.length-1){ c.groupIndex++; c.group = this._groups[c.groupIndex]; doh.util.mixin(c.group, this._additionalGroupProperties); this.ui.groupStarted(c.group); c.testIndex = 0; } else { this.ui.report(); return false; } } c.test = c.group.tests[c.testIndex]; return true; }, _runNextTest:function(){ // summary: Only called from internally after a test has finished. if (this._isPaused){ return; } if (this._selectNextTest()){ this._runTest(); } }, _runTest:function(){ // summary: This executes the current test. // description: This method starts the "test" method of the test object // and finishes by setting the internal state "_testInFlight" to true, // which is resolved by the call to "_runNextTest()" which // automatically happens after the (asynchronous) test has "landed". var g = this._current.group, t = this._current.test; this.ui.testStarted(g, t); // let doh reference "this.group.thinger..." which can be set by // another test or group-level setUp function t.group = g; var deferred = new doh.Deferred(), - assertWrapperObject = this._getAssertWrapper(deferred); + assertWrapperObject = this._getAssertWrapper(deferred), + setUpError = null; if(t.setUp){ - t.setUp(assertWrapperObject); + try{ + t.setUp(assertWrapperObject); + }catch(setUpError){ + deferred.errback(new Error('setUp() threw an error: ' + setUpError)); + } } if(!t[this.config.testFunctionName]){ t[this.config.testFunctionName] = function(){deferred.errback(new Error("Test missing."));} } deferred.groupName = g.name; deferred.test = t; deferred.addErrback(function(err){ if (err instanceof doh.assert.Failure){ g.numFailures++; doh._numFailures++; doh.ui.testFailure(g, t, err); } else { g.numErrors++; doh._numErrors++; doh.ui.testError(g, t, err); } }); var retEnd = function(){ t.endTime = new Date(); g.numTestsExecuted++; doh._numTestsExecuted++; if(t.tearDown){ - t.tearDown(assertWrapperObject); + try{ // Catching tearDown() errors won't make the entire suite stall. + t.tearDown(assertWrapperObject); + }catch(tearDownError){ +// FIXXXME handle this case. But how? see TODO.txt for more comments. + } } doh.ui.testFinished(g, t, deferred.results[0]); // Is this the last test in the current group? var c = doh._current; if (c.testIndex == c.group.tests.length-1){ doh.ui.groupFinished(g); } } var timer = setTimeout(function(){ deferred.errback(new Error("test timeout in " + t.name.toString())); }, t.timeout || doh._defaultTimeout); deferred.addBoth(function(){ // Copy over the result if an asynchronous test has writte a result. // It must be available through the test object. // TODO maybe copy over all additional properties, compare to which props assertWrapperObject had upon creation and what new ones had been added, pass them all to t.* if (assertWrapperObject.result){ t.result = assertWrapperObject.result; } clearTimeout(timer); retEnd(); doh._testInFlight = false; setTimeout(doh.util.hitch(doh, "_runNextTest"), 1); }); this._testInFlight = true; - t.startTime = new Date(); - try{ - t.result = t[this.config.testFunctionName](assertWrapperObject); - }catch(err){ - deferred.errback(err); + if (!setUpError){ + t.startTime = new Date(); + try{ + t.result = t[this.config.testFunctionName](assertWrapperObject); + }catch(err){ + deferred.errback(err); + } } } } diff --git a/selftests.js b/selftests.js index 7862baa..de7340f 100644 --- a/selftests.js +++ b/selftests.js @@ -1,317 +1,341 @@ // TODO write a test that verifies that the test run in the order as added. // Write tets for setUp and tearDown - +//* doh.register("Synchronously written tests.", [ // // assertTrue // { name:"fail: assertTrue", test:function(t){ t.assertTrue(false); } },{ name:"success: assertTrue", test:function(t){ t.assertTrue(true); } }, // // assertFalse // { name:"fail: assertFalse", test:function(t){ t.assertFalse(true); } },{ name:"success: assertFalse", test:function(t){ t.assertFalse(false); } }, // // assertEqual // { name:"fail: assertEqual bools", test:function(t){ t.assertEqual(true, false); } },{ name:"success: assertFalse bools", test:function(t){ t.assertEqual(true, true); } }, { name:"fail: assertEqual numbers", test:function(t){ t.assertEqual(1, "2"); } },{ name:"success: assertEqual numbers", test:function(t){ t.assertEqual(1, "1"); } }, { name:"fail: assertEqual arrays", test:function(t){ t.assertEqual([1,2], [2,1]); } },{ name:"success: assertEqual arrays", test:function(t){ t.assertEqual([2,3], [2,3]); } }, { // A missing assert call. name:"error: timeout, assert() missing", test:function(t){ } },{ // This test will fail, because it has no implementation of the test method. name:"error: test() missing" } ] ); doh.register("Asynchronous tests.", [ { // Inside of an asynch test case you can (and should) still use the assert() methods. // No return necessary anymore!!! name:"fail: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(false); }, 1000); } }, { name:"success: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, { name:"error: timeout", timeout:100, // This timeout is shorter than the setTimeout below, this test should fail. test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, ] ); var timeDiff; doh.register("Test doh.pause()", [ { // Test that calling pause() from inside a test does pause the test // suite and do also test that run() does continue. name:"success: pause after this test (and run again)", test:function(t){ t.assertTrue(true); doh.pause(); timeDiff = new Date().getTime(); setTimeout(function(){doh.run()}, 3500); } }, { // This test basically measures the time that the test before had // paused the test execution and it should be between 3-4 secs. name:"success: measure paused time", test:function(t){ var diff = new Date().getTime() - timeDiff t.assertTrue(diff > 3000 && diff < 4000, "The pause should be between 3-4 seconds."); } }, ] ); // // Test "config" parameter. // doh.register("Config parameter tests", [ { name:"success: 'testFunctionName'", setUp:function(){ this._actualTestFunctionName = doh.config.testFunctionName; doh.config.testFunctionName = "myTestFunctionName"; }, myTestFunctionName:function(t){ t.assertTrue(true); }, tearDown:function(){ doh.config.testFunctionName = this._actualTestFunctionName; } }, { name:"success: reset 'testFunctionName'", test:function(t){ t.assertTrue(true); } } ] ); // When writing a GUI for the tests it happens that you also want to show the // test cases that succeeded and maybe with what value, that is what the return // values are for. // E.g. // test:function(){ // assertEqual(expectedGeoLocation, actualGeoLocation); // return actualGeoLocation; // } // Returning the actual value allows the doh.ui methods to show this value to the user. (function(){ var testObject = { // We will check if this object has the return value set after the test. name:"success: Simple return", test:function(t){ t.assertTrue(true); return "jojo"; } }; doh.register("Return values", [ testObject, { name:"success: Verify return value from last test", test:function(t){ t.assertEqual(testObject.result, "jojo"); } }, ] ); // Test a bug that was in the tests, which didn't pass the value returned by a test // to the doh.ui.testFinished() function, because that function was called BEFORE // the returned value was set into the test data. A pretty tricky asynch // problem. The following is the test to verify that it is fixed. var resultValue = null, oldTestFinished; doh.register("Return value, asynch bug", [ { name:"success: Verify return value from last test", setUp:function(){ // We have to override the testFinished() before we call assert() // because with the bug assert() triggered the testFinished() // before return was executed. oldTestFinished = doh.ui.testFinished; // Backup the old testFinished(). doh.ui.testFinished = function(group, test){ resultValue = test.result; oldTestFinished.apply(doh.ui, arguments); } }, test:function(t){ t.assertTrue(true); return "EXPECT ME"; } }, { name:"success: Verify result from last test.", setUp:function(){ doh.ui.testFinished = oldTestFinished; }, test:function(t){ t.assertEqual("EXPECT ME", resultValue); } } ] ); })(); // If the test contains asynch parts you can set the "result" property of the test explicitly instead // of returning a value, like so. (function(){ var testObject = { // We will check if this object has the return value set after the test. name:"success: Simple return", test:function(t){ setTimeout(function(){ t.assertTrue(true); t.result = "jaja"; }, 100); } }; doh.register("Return values in asynch test", [ testObject, { name:"success: Verify result value from last test", test:function(t){ t.assertEqual(testObject.result, "jaja"); } }, ] ); })(); +//*/ /* doh.register("Multiple asserts", [ { name:"success: some asserts", test:function(t){ t.assertTrue(true); t.assertEqual(1, 1); t.assertError(new Error()); } }, { name:"fail: last assert fails", test:function(t){ t.assertTrue(true); t.assertEqual(1, 1); t.assertError(new Error()); // FIXXXME multiple asserts dont work yet :( t.assertTrue(false); } }, { name:"fail: last assert fails", timeout:12*1000, test:function(t){ t.assertTrue(true); setTimeout(function(){ t.numAsserts++; t.assertTrue(false); }, 10 * 1000); } }, ] ); write a test which tests that the test is aborted in the place where the first failure occurs, e.g. assertTrue(false); window = undefined; // this should NEVER be executed because the test function should be aborted above!!!!!! assert(undefined, window); //*/ + +(function(){ + doh.register("setUp()/tearDown() throw an error", [ + { + name:"error: setUp() throws an error, test won't execute.", + setUp:function(){ + throw new Error("Nasty error."); + }, + test:function(t){ + t.assertTrue(true); + } + }, + { + name:"success: tearDown() throws an error ... not sure what to do", + test:function(t){ + t.assertTrue(true); + }, + tearDown:function(){ + throw new Error("Nasty error."); + } + } + ]); +})(); \ No newline at end of file
wolframkriesing/doh2
39d058314caab0819d910eb3c9432844c53c539d
+ add success+failure method directly to the test object which is passed to the test function, so tests can explicitly made to fail/succeed
diff --git a/doh.js b/doh.js index 2b1ef75..a0e0aa8 100644 --- a/doh.js +++ b/doh.js @@ -1,217 +1,231 @@ doh = { // This is a temporary structure which points to the current data. _current:{ group:null, groupIndex:-1, test:null, testIndex:-1 }, // A helper property, which stores a reference to a test group by name. _groupsByName:{}, // Statistical data. _numTests:0, // The total number of tests. _numTestsExecuted:0, // Number of tests already executed. // Stats about the test results. _numErrors:0, _numFailures:0, // _isPaused:false, _defaultTimeout:1000, _testInFlight:false, // The groups must be an array, since an object does not necessarily maintain // it's order, but tests should be executed in the order as added. // This might become even more important when test dependencies will be added, // which means only execute test2 if test1 succeeded. _groups:[], _additionalGroupProperties:{ numTestsExecuted:0, numFailures:0, numErrors:0 }, pause:function(){ this._isPaused = true; }, register:function(groupName, tests){ // summary: Register the given tests to the group with the given name. // description: The tests are internally stored in "_groups", an array // which contains all the tests per group. The new tests are added // to the group with the given name, if it didnt exist yet it is created. var group = null; if (this._groupsByName[groupName]){ group = this._groupsByName[groupName]; } else { this._groups.push({name:groupName, tests:[]}); group = this._groupsByName[groupName] = this._groups[this._groups.length-1]; } for (var i=0, l=tests.length, t; i<l; i++){ group.tests.push(tests[i]); } this._numTests += tests.length; }, run:function(){ if (this._current.group===null){ this.ui.started(); } this._isPaused = false; if (this._testInFlight){ return; } this._runNextTest(); }, _getAssertWrapper:function(d){ // summary: This returns an object which provides all the assert methods, and wraps a Deferred instance. // description: Why that? The interface for doh tests should be the same // for synchronous and asynchronous tests. The old version required // you to "know" and "think" when writing asynch tests, and the // assert methods had not been available directly when writing // asynchronous tests, you had to use doh.callback/errback. // This allows to ONLY use assert*() methods. See the selftests // for examples. var myT = new function(){ this._assertClosure = function(method, args){ // If the Deferred instance is already "done", means callback or errback // had already been called don't do it again. // This might be the case when e.g. the test timed out. if (d.fired > -1){ console.log('FIXXXXXME multiple asserts or timeout ... d.fired = ', d.fired, "GROUP and TEST: '", d.test.group.name, "' " , d.test.name); return; } try{ var ret = doh.assert[method].apply(doh, args); d.callback(ret || true); }catch(e){ d.errback(e); } }; + this.success = function(msg){ + // This function can be used to directly make a test succeed. +//TODO write selftest for it!!!!!!!!! + d.test.result = msg; + d.callback(msg); + }; + this.failure = function(msg){ +//TODO write selftest for it!!!!!!!!! + d.errback(new doh.assert.Failure(msg)); + }; var that = this; for (var methodName in doh.assert){ if (methodName.indexOf("assert")===0){ this[methodName] = (function(methodName){return function(){ // Make sure the current callstack is worked off before // returning from any assert() method, we do this by // setTimeout(). The bug was that assert() didn't make the // test execute the return statement (if one was in there) // before the test ended, this fixes it. setTimeout(doh.util.hitch(that, "_assertClosure", methodName, arguments), 1); }})(methodName); } } }; return myT; }, _selectNextTest:function(){ var c = this._current; // Is there a test left in this group? if (c.group && c.testIndex < c.group.tests.length-1){ c.testIndex++; } else { // First test in the next group, if there is another group. if (c.groupIndex < this._groups.length-1){ c.groupIndex++; c.group = this._groups[c.groupIndex]; doh.util.mixin(c.group, this._additionalGroupProperties); this.ui.groupStarted(c.group); c.testIndex = 0; } else { this.ui.report(); return false; } } c.test = c.group.tests[c.testIndex]; return true; }, _runNextTest:function(){ // summary: Only called from internally after a test has finished. if (this._isPaused){ return; } if (this._selectNextTest()){ this._runTest(); } }, _runTest:function(){ // summary: This executes the current test. // description: This method starts the "test" method of the test object // and finishes by setting the internal state "_testInFlight" to true, // which is resolved by the call to "_runNextTest()" which // automatically happens after the (asynchronous) test has "landed". var g = this._current.group, t = this._current.test; this.ui.testStarted(g, t); // let doh reference "this.group.thinger..." which can be set by // another test or group-level setUp function t.group = g; var deferred = new doh.Deferred(), assertWrapperObject = this._getAssertWrapper(deferred); if(t.setUp){ t.setUp(assertWrapperObject); } if(!t[this.config.testFunctionName]){ t[this.config.testFunctionName] = function(){deferred.errback(new Error("Test missing."));} } deferred.groupName = g.name; deferred.test = t; deferred.addErrback(function(err){ if (err instanceof doh.assert.Failure){ g.numFailures++; doh._numFailures++; doh.ui.testFailure(g, t, err); } else { g.numErrors++; doh._numErrors++; doh.ui.testError(g, t, err); } }); var retEnd = function(){ t.endTime = new Date(); g.numTestsExecuted++; doh._numTestsExecuted++; if(t.tearDown){ t.tearDown(assertWrapperObject); } doh.ui.testFinished(g, t, deferred.results[0]); // Is this the last test in the current group? var c = doh._current; if (c.testIndex == c.group.tests.length-1){ doh.ui.groupFinished(g); } } var timer = setTimeout(function(){ deferred.errback(new Error("test timeout in " + t.name.toString())); }, t.timeout || doh._defaultTimeout); deferred.addBoth(function(){ // Copy over the result if an asynchronous test has writte a result. // It must be available through the test object. // TODO maybe copy over all additional properties, compare to which props assertWrapperObject had upon creation and what new ones had been added, pass them all to t.* if (assertWrapperObject.result){ t.result = assertWrapperObject.result; } clearTimeout(timer); retEnd(); doh._testInFlight = false; setTimeout(doh.util.hitch(doh, "_runNextTest"), 1); }); this._testInFlight = true; t.startTime = new Date(); - t.result = t[this.config.testFunctionName](assertWrapperObject); + try{ + t.result = t[this.config.testFunctionName](assertWrapperObject); + }catch(err){ + deferred.errback(err); + } } } diff --git a/selftests.js b/selftests.js index 649125b..7862baa 100644 --- a/selftests.js +++ b/selftests.js @@ -1,312 +1,317 @@ // TODO write a test that verifies that the test run in the order as added. // Write tets for setUp and tearDown doh.register("Synchronously written tests.", [ // // assertTrue // { name:"fail: assertTrue", test:function(t){ t.assertTrue(false); } },{ name:"success: assertTrue", test:function(t){ t.assertTrue(true); } }, // // assertFalse // { name:"fail: assertFalse", test:function(t){ t.assertFalse(true); } },{ name:"success: assertFalse", test:function(t){ t.assertFalse(false); } }, // // assertEqual // { name:"fail: assertEqual bools", test:function(t){ t.assertEqual(true, false); } },{ name:"success: assertFalse bools", test:function(t){ t.assertEqual(true, true); } }, { name:"fail: assertEqual numbers", test:function(t){ t.assertEqual(1, "2"); } },{ name:"success: assertEqual numbers", test:function(t){ t.assertEqual(1, "1"); } }, { name:"fail: assertEqual arrays", test:function(t){ t.assertEqual([1,2], [2,1]); } },{ name:"success: assertEqual arrays", test:function(t){ t.assertEqual([2,3], [2,3]); } }, { // A missing assert call. name:"error: timeout, assert() missing", test:function(t){ } },{ // This test will fail, because it has no implementation of the test method. name:"error: test() missing" } ] ); doh.register("Asynchronous tests.", [ { // Inside of an asynch test case you can (and should) still use the assert() methods. // No return necessary anymore!!! name:"fail: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(false); }, 1000); } }, { name:"success: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, { name:"error: timeout", timeout:100, // This timeout is shorter than the setTimeout below, this test should fail. test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, ] ); var timeDiff; doh.register("Test doh.pause()", [ { // Test that calling pause() from inside a test does pause the test // suite and do also test that run() does continue. name:"success: pause after this test (and run again)", test:function(t){ t.assertTrue(true); doh.pause(); timeDiff = new Date().getTime(); setTimeout(function(){doh.run()}, 3500); } }, { // This test basically measures the time that the test before had // paused the test execution and it should be between 3-4 secs. name:"success: measure paused time", test:function(t){ var diff = new Date().getTime() - timeDiff t.assertTrue(diff > 3000 && diff < 4000, "The pause should be between 3-4 seconds."); } }, ] ); // // Test "config" parameter. // doh.register("Config parameter tests", [ { name:"success: 'testFunctionName'", setUp:function(){ this._actualTestFunctionName = doh.config.testFunctionName; doh.config.testFunctionName = "myTestFunctionName"; }, myTestFunctionName:function(t){ t.assertTrue(true); }, tearDown:function(){ doh.config.testFunctionName = this._actualTestFunctionName; } }, { name:"success: reset 'testFunctionName'", test:function(t){ t.assertTrue(true); } } ] ); // When writing a GUI for the tests it happens that you also want to show the // test cases that succeeded and maybe with what value, that is what the return // values are for. // E.g. // test:function(){ // assertEqual(expectedGeoLocation, actualGeoLocation); // return actualGeoLocation; // } // Returning the actual value allows the doh.ui methods to show this value to the user. (function(){ var testObject = { // We will check if this object has the return value set after the test. name:"success: Simple return", test:function(t){ t.assertTrue(true); return "jojo"; } }; doh.register("Return values", [ testObject, { name:"success: Verify return value from last test", test:function(t){ t.assertEqual(testObject.result, "jojo"); } }, ] ); // Test a bug that was in the tests, which didn't pass the value returned by a test // to the doh.ui.testFinished() function, because that function was called BEFORE // the returned value was set into the test data. A pretty tricky asynch // problem. The following is the test to verify that it is fixed. var resultValue = null, oldTestFinished; doh.register("Return value, asynch bug", [ { name:"success: Verify return value from last test", setUp:function(){ // We have to override the testFinished() before we call assert() // because with the bug assert() triggered the testFinished() // before return was executed. oldTestFinished = doh.ui.testFinished; // Backup the old testFinished(). doh.ui.testFinished = function(group, test){ resultValue = test.result; oldTestFinished.apply(doh.ui, arguments); } }, test:function(t){ t.assertTrue(true); return "EXPECT ME"; } }, { name:"success: Verify result from last test.", setUp:function(){ doh.ui.testFinished = oldTestFinished; }, test:function(t){ t.assertEqual("EXPECT ME", resultValue); } } ] ); })(); // If the test contains asynch parts you can set the "result" property of the test explicitly instead // of returning a value, like so. (function(){ var testObject = { // We will check if this object has the return value set after the test. name:"success: Simple return", test:function(t){ setTimeout(function(){ t.assertTrue(true); t.result = "jaja"; }, 100); } }; doh.register("Return values in asynch test", [ testObject, { name:"success: Verify result value from last test", test:function(t){ t.assertEqual(testObject.result, "jaja"); } }, ] ); })(); /* doh.register("Multiple asserts", [ { name:"success: some asserts", test:function(t){ t.assertTrue(true); t.assertEqual(1, 1); t.assertError(new Error()); } }, { name:"fail: last assert fails", test:function(t){ t.assertTrue(true); t.assertEqual(1, 1); t.assertError(new Error()); // FIXXXME multiple asserts dont work yet :( t.assertTrue(false); } }, { name:"fail: last assert fails", timeout:12*1000, test:function(t){ t.assertTrue(true); setTimeout(function(){ t.numAsserts++; t.assertTrue(false); }, 10 * 1000); } }, ] ); +write a test which tests that the test is aborted in the place where the first failure occurs, e.g. + assertTrue(false); + window = undefined; // this should NEVER be executed because the test function should be aborted above!!!!!! + assert(undefined, window); + //*/
wolframkriesing/doh2
9b544f0bc43a42fa5287633448240ed253a85966
+ better naming and code reuse, which makes extending/overriding it easier too
diff --git a/doh.js b/doh.js index d48f57a..2b1ef75 100644 --- a/doh.js +++ b/doh.js @@ -1,219 +1,217 @@ doh = { // This is a temporary structure which points to the current data. _current:{ group:null, groupIndex:-1, test:null, testIndex:-1 }, // A helper property, which stores a reference to a test group by name. _groupsByName:{}, // Statistical data. _numTests:0, // The total number of tests. _numTestsExecuted:0, // Number of tests already executed. // Stats about the test results. _numErrors:0, _numFailures:0, // _isPaused:false, _defaultTimeout:1000, _testInFlight:false, // The groups must be an array, since an object does not necessarily maintain // it's order, but tests should be executed in the order as added. // This might become even more important when test dependencies will be added, // which means only execute test2 if test1 succeeded. _groups:[], _additionalGroupProperties:{ numTestsExecuted:0, numFailures:0, numErrors:0 }, pause:function(){ this._isPaused = true; }, register:function(groupName, tests){ // summary: Register the given tests to the group with the given name. // description: The tests are internally stored in "_groups", an array // which contains all the tests per group. The new tests are added // to the group with the given name, if it didnt exist yet it is created. var group = null; if (this._groupsByName[groupName]){ group = this._groupsByName[groupName]; } else { this._groups.push({name:groupName, tests:[]}); group = this._groupsByName[groupName] = this._groups[this._groups.length-1]; } for (var i=0, l=tests.length, t; i<l; i++){ group.tests.push(tests[i]); } this._numTests += tests.length; }, run:function(){ if (this._current.group===null){ this.ui.started(); } this._isPaused = false; if (this._testInFlight){ return; } - if (this._makeNextTestCurrent()){ - this._runTest(); - } + this._runNextTest(); }, _getAssertWrapper:function(d){ // summary: This returns an object which provides all the assert methods, and wraps a Deferred instance. // description: Why that? The interface for doh tests should be the same // for synchronous and asynchronous tests. The old version required // you to "know" and "think" when writing asynch tests, and the // assert methods had not been available directly when writing // asynchronous tests, you had to use doh.callback/errback. // This allows to ONLY use assert*() methods. See the selftests // for examples. var myT = new function(){ this._assertClosure = function(method, args){ // If the Deferred instance is already "done", means callback or errback // had already been called don't do it again. // This might be the case when e.g. the test timed out. if (d.fired > -1){ console.log('FIXXXXXME multiple asserts or timeout ... d.fired = ', d.fired, "GROUP and TEST: '", d.test.group.name, "' " , d.test.name); return; } try{ var ret = doh.assert[method].apply(doh, args); d.callback(ret || true); }catch(e){ d.errback(e); } }; var that = this; for (var methodName in doh.assert){ if (methodName.indexOf("assert")===0){ this[methodName] = (function(methodName){return function(){ // Make sure the current callstack is worked off before // returning from any assert() method, we do this by // setTimeout(). The bug was that assert() didn't make the // test execute the return statement (if one was in there) // before the test ended, this fixes it. setTimeout(doh.util.hitch(that, "_assertClosure", methodName, arguments), 1); }})(methodName); } } }; return myT; }, - _makeNextTestCurrent:function(){ + _selectNextTest:function(){ var c = this._current; // Is there a test left in this group? if (c.group && c.testIndex < c.group.tests.length-1){ c.testIndex++; } else { // First test in the next group, if there is another group. if (c.groupIndex < this._groups.length-1){ c.groupIndex++; c.group = this._groups[c.groupIndex]; doh.util.mixin(c.group, this._additionalGroupProperties); this.ui.groupStarted(c.group); c.testIndex = 0; } else { this.ui.report(); return false; } } c.test = c.group.tests[c.testIndex]; return true; }, _runNextTest:function(){ // summary: Only called from internally after a test has finished. if (this._isPaused){ return; } - if (this._makeNextTestCurrent()){ + if (this._selectNextTest()){ this._runTest(); } }, _runTest:function(){ // summary: This executes the current test. // description: This method starts the "test" method of the test object // and finishes by setting the internal state "_testInFlight" to true, // which is resolved by the call to "_runNextTest()" which // automatically happens after the (asynchronous) test has "landed". var g = this._current.group, t = this._current.test; this.ui.testStarted(g, t); // let doh reference "this.group.thinger..." which can be set by // another test or group-level setUp function t.group = g; var deferred = new doh.Deferred(), assertWrapperObject = this._getAssertWrapper(deferred); if(t.setUp){ t.setUp(assertWrapperObject); } if(!t[this.config.testFunctionName]){ t[this.config.testFunctionName] = function(){deferred.errback(new Error("Test missing."));} } deferred.groupName = g.name; deferred.test = t; deferred.addErrback(function(err){ if (err instanceof doh.assert.Failure){ g.numFailures++; doh._numFailures++; doh.ui.testFailure(g, t, err); } else { g.numErrors++; doh._numErrors++; doh.ui.testError(g, t, err); } }); var retEnd = function(){ t.endTime = new Date(); g.numTestsExecuted++; doh._numTestsExecuted++; if(t.tearDown){ t.tearDown(assertWrapperObject); } doh.ui.testFinished(g, t, deferred.results[0]); // Is this the last test in the current group? var c = doh._current; if (c.testIndex == c.group.tests.length-1){ doh.ui.groupFinished(g); } } var timer = setTimeout(function(){ deferred.errback(new Error("test timeout in " + t.name.toString())); }, t.timeout || doh._defaultTimeout); deferred.addBoth(function(){ // Copy over the result if an asynchronous test has writte a result. // It must be available through the test object. // TODO maybe copy over all additional properties, compare to which props assertWrapperObject had upon creation and what new ones had been added, pass them all to t.* if (assertWrapperObject.result){ t.result = assertWrapperObject.result; } clearTimeout(timer); retEnd(); doh._testInFlight = false; setTimeout(doh.util.hitch(doh, "_runNextTest"), 1); }); this._testInFlight = true; t.startTime = new Date(); t.result = t[this.config.testFunctionName](assertWrapperObject); } }
wolframkriesing/doh2
10339bc6ff4ad3d932ba50bfec4bf285efd5b655
+ added config, bugfixes + added config tests
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fc0fdfd --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.kpf diff --git a/selftest.html b/selftest.html index 0ea6292..a7e5efe 100644 --- a/selftest.html +++ b/selftest.html @@ -1,48 +1,49 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>D.O.H. v2</title> <meta http-equiv="content-type" content="text/html; charset=utf-8"> </head> <body> <h1>Self tests</h1> <p>This will run several tests using this library, don't be scared when some of the test fail, this is intentionally, to test the test suite itself.</p> <h2>Your result should look like this:</h2> <pre style="font-size: large; color: red;"> <span id="numTestsRan">0</span> tests ran, <span id="numFailures">0</span> failures, <span id="numErrors">0</span> errors </pre> <script type="text/javascript" src="doh.js"></script> + <script type="text/javascript" src="config.js"></script> <script type="text/javascript" src="util.js"></script> <script type="text/javascript" src="deferred.js"></script> <script type="text/javascript" src="assert.js"></script> <script type="text/javascript" src="ui.js"></script> <script type="text/javascript" src="selftests.js"></script> <script type="text/javascript"> // Go through all the tests and find out how many should fail // and how many should pass, the name of each test tells. // And fill the HTML above appropriately. var numTests = 0, numFailures = 0, numErrors = 0; for (var i=0, g; g=doh._groups[i]; i++){ numTests += g.tests.length; for (var j=0, t; t=g.tests[j]; j++){ if (t.name.indexOf("fail: ")===0){ numFailures++; } else if (t.name.indexOf("error: ")===0){ numErrors++; } } } document.getElementById("numTestsRan").innerHTML = numTests; document.getElementById("numFailures").innerHTML = numFailures; document.getElementById("numErrors").innerHTML = numErrors; doh.run(); </script> </body> </html> diff --git a/selftests.js b/selftests.js index 1fac6a8..649125b 100644 --- a/selftests.js +++ b/selftests.js @@ -1,210 +1,312 @@ // TODO write a test that verifies that the test run in the order as added. // Write tets for setUp and tearDown doh.register("Synchronously written tests.", [ // // assertTrue // { name:"fail: assertTrue", test:function(t){ t.assertTrue(false); } },{ name:"success: assertTrue", test:function(t){ t.assertTrue(true); } }, // // assertFalse // { name:"fail: assertFalse", test:function(t){ t.assertFalse(true); } },{ name:"success: assertFalse", test:function(t){ t.assertFalse(false); } }, // // assertEqual // { name:"fail: assertEqual bools", test:function(t){ t.assertEqual(true, false); } },{ name:"success: assertFalse bools", test:function(t){ t.assertEqual(true, true); } }, { name:"fail: assertEqual numbers", test:function(t){ t.assertEqual(1, "2"); } },{ name:"success: assertEqual numbers", test:function(t){ t.assertEqual(1, "1"); } }, { name:"fail: assertEqual arrays", test:function(t){ t.assertEqual([1,2], [2,1]); } },{ name:"success: assertEqual arrays", test:function(t){ t.assertEqual([2,3], [2,3]); } }, { // A missing assert call. name:"error: timeout, assert() missing", test:function(t){ } },{ // This test will fail, because it has no implementation of the test method. name:"error: test() missing" } ] ); - doh.register("Asynchronous tests.", [ { // Inside of an asynch test case you can (and should) still use the assert() methods. // No return necessary anymore!!! name:"fail: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(false); }, 1000); } }, { name:"success: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, { name:"error: timeout", timeout:100, // This timeout is shorter than the setTimeout below, this test should fail. test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, ] ); var timeDiff; doh.register("Test doh.pause()", [ { // Test that calling pause() from inside a test does pause the test // suite and do also test that run() does continue. name:"success: pause after this test (and run again)", test:function(t){ t.assertTrue(true); doh.pause(); timeDiff = new Date().getTime(); setTimeout(function(){doh.run()}, 3500); } }, { // This test basically measures the time that the test before had // paused the test execution and it should be between 3-4 secs. name:"success: measure paused time", test:function(t){ var diff = new Date().getTime() - timeDiff t.assertTrue(diff > 3000 && diff < 4000, "The pause should be between 3-4 seconds."); } }, ] ); +// +// Test "config" parameter. +// +doh.register("Config parameter tests", + [ + { + name:"success: 'testFunctionName'", + setUp:function(){ + this._actualTestFunctionName = doh.config.testFunctionName; + doh.config.testFunctionName = "myTestFunctionName"; + }, + myTestFunctionName:function(t){ + t.assertTrue(true); + }, + tearDown:function(){ + doh.config.testFunctionName = this._actualTestFunctionName; + } + }, + { + name:"success: reset 'testFunctionName'", + test:function(t){ + t.assertTrue(true); + } + } + ] +); + + + // When writing a GUI for the tests it happens that you also want to show the // test cases that succeeded and maybe with what value, that is what the return // values are for. // E.g. // test:function(){ // assertEqual(expectedGeoLocation, actualGeoLocation); // return actualGeoLocation; // } // Returning the actual value allows the doh.ui methods to show this value to the user. (function(){ var testObject = { // We will check if this object has the return value set after the test. name:"success: Simple return", test:function(t){ t.assertTrue(true); return "jojo"; } }; doh.register("Return values", [ testObject, { name:"success: Verify return value from last test", test:function(t){ t.assertEqual(testObject.result, "jojo"); } }, ] ); + + // Test a bug that was in the tests, which didn't pass the value returned by a test + // to the doh.ui.testFinished() function, because that function was called BEFORE + // the returned value was set into the test data. A pretty tricky asynch + // problem. The following is the test to verify that it is fixed. + var resultValue = null, + oldTestFinished; + doh.register("Return value, asynch bug", + [ + { + name:"success: Verify return value from last test", + setUp:function(){ + // We have to override the testFinished() before we call assert() + // because with the bug assert() triggered the testFinished() + // before return was executed. + oldTestFinished = doh.ui.testFinished; // Backup the old testFinished(). + doh.ui.testFinished = function(group, test){ + resultValue = test.result; + oldTestFinished.apply(doh.ui, arguments); + } + }, + test:function(t){ + t.assertTrue(true); + return "EXPECT ME"; + } + }, + { + name:"success: Verify result from last test.", + setUp:function(){ + doh.ui.testFinished = oldTestFinished; + }, + test:function(t){ + t.assertEqual("EXPECT ME", resultValue); + } + } + ] + ); })(); + // If the test contains asynch parts you can set the "result" property of the test explicitly instead // of returning a value, like so. (function(){ var testObject = { // We will check if this object has the return value set after the test. name:"success: Simple return", test:function(t){ setTimeout(function(){ t.assertTrue(true); t.result = "jaja"; }, 100); } }; doh.register("Return values in asynch test", [ testObject, { -// Still fails :-( name:"success: Verify result value from last test", test:function(t){ t.assertEqual(testObject.result, "jaja"); } }, ] ); })(); +/* +doh.register("Multiple asserts", + [ + { + name:"success: some asserts", + test:function(t){ + t.assertTrue(true); + t.assertEqual(1, 1); + t.assertError(new Error()); + } + }, + { + name:"fail: last assert fails", + test:function(t){ + t.assertTrue(true); + t.assertEqual(1, 1); + t.assertError(new Error()); + +// FIXXXME multiple asserts dont work yet :( + t.assertTrue(false); + } + }, + { + name:"fail: last assert fails", + timeout:12*1000, + test:function(t){ + t.assertTrue(true); + setTimeout(function(){ + t.numAsserts++; + t.assertTrue(false); + }, 10 * 1000); + } + }, + ] +); + +//*/
wolframkriesing/doh2
677576c9fcaf85139fd945a60ea34687ced7e28c
+ bugfixes
diff --git a/config.js b/config.js new file mode 100644 index 0000000..112ef70 --- /dev/null +++ b/config.js @@ -0,0 +1,12 @@ +// mmmmh, if we allow filtering and only running some tests +// we have to adjust doh.register() so numTests etc. have to be adjusted too, right? +// or it will just be "wrong". +doh.config = { + filter:{ + groupName:"" + }, + + // testFunctionName: Set the function name where the test is implemented in. + testFunctionName:"test" +}; + diff --git a/doh.js b/doh.js index 519dbe8..d48f57a 100644 --- a/doh.js +++ b/doh.js @@ -1,212 +1,219 @@ doh = { // This is a temporary structure which points to the current data. _current:{ group:null, groupIndex:-1, test:null, testIndex:-1 }, // A helper property, which stores a reference to a test group by name. _groupsByName:{}, // Statistical data. _numTests:0, // The total number of tests. _numTestsExecuted:0, // Number of tests already executed. // Stats about the test results. _numErrors:0, _numFailures:0, // _isPaused:false, _defaultTimeout:1000, _testInFlight:false, // The groups must be an array, since an object does not necessarily maintain // it's order, but tests should be executed in the order as added. // This might become even more important when test dependencies will be added, // which means only execute test2 if test1 succeeded. _groups:[], _additionalGroupProperties:{ numTestsExecuted:0, numFailures:0, numErrors:0 }, pause:function(){ this._isPaused = true; }, register:function(groupName, tests){ // summary: Register the given tests to the group with the given name. // description: The tests are internally stored in "_groups", an array // which contains all the tests per group. The new tests are added // to the group with the given name, if it didnt exist yet it is created. var group = null; if (this._groupsByName[groupName]){ group = this._groupsByName[groupName]; } else { this._groups.push({name:groupName, tests:[]}); group = this._groupsByName[groupName] = this._groups[this._groups.length-1]; } for (var i=0, l=tests.length, t; i<l; i++){ group.tests.push(tests[i]); } this._numTests += tests.length; }, run:function(){ if (this._current.group===null){ this.ui.started(); } this._isPaused = false; if (this._testInFlight){ return; } if (this._makeNextTestCurrent()){ this._runTest(); } }, _getAssertWrapper:function(d){ // summary: This returns an object which provides all the assert methods, and wraps a Deferred instance. // description: Why that? The interface for doh tests should be the same // for synchronous and asynchronous tests. The old version required // you to "know" and "think" when writing asynch tests, and the // assert methods had not been available directly when writing // asynchronous tests, you had to use doh.callback/errback. // This allows to ONLY use assert*() methods. See the selftests // for examples. var myT = new function(){ this._assertClosure = function(method, args){ // If the Deferred instance is already "done", means callback or errback - // had already been called dont do it again. + // had already been called don't do it again. // This might be the case when e.g. the test timed out. if (d.fired > -1){ +console.log('FIXXXXXME multiple asserts or timeout ... d.fired = ', d.fired, "GROUP and TEST: '", d.test.group.name, "' " , d.test.name); return; } try{ var ret = doh.assert[method].apply(doh, args); d.callback(ret || true); }catch(e){ d.errback(e); } }; + var that = this; for (var methodName in doh.assert){ if (methodName.indexOf("assert")===0){ this[methodName] = (function(methodName){return function(){ - this._assertClosure(methodName, arguments); + // Make sure the current callstack is worked off before + // returning from any assert() method, we do this by + // setTimeout(). The bug was that assert() didn't make the + // test execute the return statement (if one was in there) + // before the test ended, this fixes it. + setTimeout(doh.util.hitch(that, "_assertClosure", methodName, arguments), 1); }})(methodName); } } }; return myT; }, _makeNextTestCurrent:function(){ var c = this._current; // Is there a test left in this group? if (c.group && c.testIndex < c.group.tests.length-1){ c.testIndex++; } else { // First test in the next group, if there is another group. if (c.groupIndex < this._groups.length-1){ c.groupIndex++; c.group = this._groups[c.groupIndex]; doh.util.mixin(c.group, this._additionalGroupProperties); this.ui.groupStarted(c.group); c.testIndex = 0; } else { this.ui.report(); return false; } } c.test = c.group.tests[c.testIndex]; return true; }, _runNextTest:function(){ // summary: Only called from internally after a test has finished. if (this._isPaused){ return; } if (this._makeNextTestCurrent()){ this._runTest(); } }, _runTest:function(){ // summary: This executes the current test. // description: This method starts the "test" method of the test object // and finishes by setting the internal state "_testInFlight" to true, // which is resolved by the call to "_runNextTest()" which // automatically happens after the (asynchronous) test has "landed". var g = this._current.group, t = this._current.test; this.ui.testStarted(g, t); // let doh reference "this.group.thinger..." which can be set by // another test or group-level setUp function t.group = g; var deferred = new doh.Deferred(), assertWrapperObject = this._getAssertWrapper(deferred); if(t.setUp){ t.setUp(assertWrapperObject); } - if(!t.test){ - t.test = function(){deferred.errback(new Error("Test missing."));} + if(!t[this.config.testFunctionName]){ + t[this.config.testFunctionName] = function(){deferred.errback(new Error("Test missing."));} } deferred.groupName = g.name; deferred.test = t; deferred.addErrback(function(err){ if (err instanceof doh.assert.Failure){ g.numFailures++; doh._numFailures++; doh.ui.testFailure(g, t, err); } else { g.numErrors++; doh._numErrors++; doh.ui.testError(g, t, err); } }); var retEnd = function(){ t.endTime = new Date(); g.numTestsExecuted++; doh._numTestsExecuted++; if(t.tearDown){ t.tearDown(assertWrapperObject); } doh.ui.testFinished(g, t, deferred.results[0]); // Is this the last test in the current group? var c = doh._current; if (c.testIndex == c.group.tests.length-1){ doh.ui.groupFinished(g); } } var timer = setTimeout(function(){ deferred.errback(new Error("test timeout in " + t.name.toString())); }, t.timeout || doh._defaultTimeout); deferred.addBoth(function(){ // Copy over the result if an asynchronous test has writte a result. // It must be available through the test object. // TODO maybe copy over all additional properties, compare to which props assertWrapperObject had upon creation and what new ones had been added, pass them all to t.* if (assertWrapperObject.result){ t.result = assertWrapperObject.result; } clearTimeout(timer); retEnd(); doh._testInFlight = false; setTimeout(doh.util.hitch(doh, "_runNextTest"), 1); }); this._testInFlight = true; t.startTime = new Date(); - t.result = t.test(assertWrapperObject); + t.result = t[this.config.testFunctionName](assertWrapperObject); } }
wolframkriesing/doh2
34ec971d9a1898567dd225c7585f075a4fc42d5a
+ write selftests that show how to use the return value, doesnt work from asynch yet :-(
diff --git a/README.txt b/README.txt index e950c9a..a4bf1ea 100644 --- a/README.txt +++ b/README.txt @@ -1,35 +1,37 @@ Dojo Object Harness v2 ====================== History ------- I was on the search for a JavaScript unit testing package, and kind of by accident (LOL) I stumbled across DOH, the actual dojo object harness, contained in dojo (at least currently). I started happily using it, but as you know it always comes one thing and then another which you need. So I started adding and adding and felt that the (old) doh was just not flexible enough and had some drawbacks. Therefore I pulled out the best pieces and glued it back together and out came this. Features -------- The features the (old) doh provides and doh2 does too: * asynchronous tests * assert functions Features doh2 added or fixed * streamlined synch and asynch test writing, no notable difference for the test writer anymore - much easier * no need to know about doh.Deferred anymore, it's all wrapped in the test object passed to the test function, just use assert*() everywhere * make doh.pause() work again * doh.pause() can also be used inside a test to stop the test run from within a test * allow returning values, such as test results for the good case +* namespaced all doh functionalities, and separated them into multiple files + doh, doh.assert, doh.util, doh.Deferred Examples -------- See the file "selftests.js" it provides tests with extensive explaination. diff --git a/selftests.js b/selftests.js index 4c6002a..1fac6a8 100644 --- a/selftests.js +++ b/selftests.js @@ -1,147 +1,210 @@ +// TODO write a test that verifies that the test run in the order as added. +// Write tets for setUp and tearDown doh.register("Synchronously written tests.", [ // // assertTrue // { name:"fail: assertTrue", test:function(t){ t.assertTrue(false); } },{ name:"success: assertTrue", test:function(t){ t.assertTrue(true); } }, // // assertFalse // { name:"fail: assertFalse", test:function(t){ t.assertFalse(true); } },{ name:"success: assertFalse", test:function(t){ t.assertFalse(false); } }, // // assertEqual // { name:"fail: assertEqual bools", test:function(t){ t.assertEqual(true, false); } },{ name:"success: assertFalse bools", test:function(t){ t.assertEqual(true, true); } }, { name:"fail: assertEqual numbers", test:function(t){ t.assertEqual(1, "2"); } },{ name:"success: assertEqual numbers", test:function(t){ t.assertEqual(1, "1"); } }, { name:"fail: assertEqual arrays", test:function(t){ t.assertEqual([1,2], [2,1]); } },{ name:"success: assertEqual arrays", test:function(t){ t.assertEqual([2,3], [2,3]); } }, { // A missing assert call. name:"error: timeout, assert() missing", test:function(t){ } },{ // This test will fail, because it has no implementation of the test method. name:"error: test() missing" } ] ); + doh.register("Asynchronous tests.", [ { // Inside of an asynch test case you can (and should) still use the assert() methods. // No return necessary anymore!!! name:"fail: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(false); }, 1000); } }, { name:"success: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, { name:"error: timeout", timeout:100, // This timeout is shorter than the setTimeout below, this test should fail. test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, ] ); var timeDiff; doh.register("Test doh.pause()", [ { // Test that calling pause() from inside a test does pause the test // suite and do also test that run() does continue. name:"success: pause after this test (and run again)", test:function(t){ t.assertTrue(true); doh.pause(); timeDiff = new Date().getTime(); setTimeout(function(){doh.run()}, 3500); } }, { // This test basically measures the time that the test before had // paused the test execution and it should be between 3-4 secs. name:"success: measure paused time", test:function(t){ var diff = new Date().getTime() - timeDiff t.assertTrue(diff > 3000 && diff < 4000, "The pause should be between 3-4 seconds."); } }, ] -); \ No newline at end of file +); + +// When writing a GUI for the tests it happens that you also want to show the +// test cases that succeeded and maybe with what value, that is what the return +// values are for. +// E.g. +// test:function(){ +// assertEqual(expectedGeoLocation, actualGeoLocation); +// return actualGeoLocation; +// } +// Returning the actual value allows the doh.ui methods to show this value to the user. + +(function(){ + var testObject = { + // We will check if this object has the return value set after the test. + name:"success: Simple return", + test:function(t){ + t.assertTrue(true); + return "jojo"; + } + }; + doh.register("Return values", + [ + testObject, + { + name:"success: Verify return value from last test", + test:function(t){ + t.assertEqual(testObject.result, "jojo"); + } + }, + ] + ); +})(); + +// If the test contains asynch parts you can set the "result" property of the test explicitly instead +// of returning a value, like so. +(function(){ + var testObject = { + // We will check if this object has the return value set after the test. + name:"success: Simple return", + test:function(t){ + setTimeout(function(){ + t.assertTrue(true); + t.result = "jaja"; + }, 100); + } + }; + doh.register("Return values in asynch test", + [ + testObject, + { +// Still fails :-( + name:"success: Verify result value from last test", + test:function(t){ + t.assertEqual(testObject.result, "jaja"); + } + }, + ] + ); +})(); +
wolframkriesing/doh2
35f3eadb66712cf4e16e8d787ea81ce503e4b597
+ simplify stuff a bit and leave the test object untouched
diff --git a/doh.js b/doh.js index fcf8a72..519dbe8 100644 --- a/doh.js +++ b/doh.js @@ -1,214 +1,212 @@ doh = { // This is a temporary structure which points to the current data. _current:{ group:null, groupIndex:-1, test:null, testIndex:-1 }, // A helper property, which stores a reference to a test group by name. _groupsByName:{}, // Statistical data. _numTests:0, // The total number of tests. _numTestsExecuted:0, // Number of tests already executed. // Stats about the test results. _numErrors:0, _numFailures:0, // _isPaused:false, _defaultTimeout:1000, _testInFlight:false, // The groups must be an array, since an object does not necessarily maintain // it's order, but tests should be executed in the order as added. // This might become even more important when test dependencies will be added, // which means only execute test2 if test1 succeeded. _groups:[], _additionalGroupProperties:{ numTestsExecuted:0, numFailures:0, numErrors:0 }, pause:function(){ this._isPaused = true; }, register:function(groupName, tests){ // summary: Register the given tests to the group with the given name. // description: The tests are internally stored in "_groups", an array // which contains all the tests per group. The new tests are added // to the group with the given name, if it didnt exist yet it is created. var group = null; if (this._groupsByName[groupName]){ group = this._groupsByName[groupName]; } else { this._groups.push({name:groupName, tests:[]}); group = this._groupsByName[groupName] = this._groups[this._groups.length-1]; } for (var i=0, l=tests.length, t; i<l; i++){ - t = {}; - doh.util.mixin(t, tests[i]); - group.tests.push(t); + group.tests.push(tests[i]); } this._numTests += tests.length; }, run:function(){ if (this._current.group===null){ this.ui.started(); } this._isPaused = false; if (this._testInFlight){ return; } if (this._makeNextTestCurrent()){ this._runTest(); } }, _getAssertWrapper:function(d){ // summary: This returns an object which provides all the assert methods, and wraps a Deferred instance. // description: Why that? The interface for doh tests should be the same // for synchronous and asynchronous tests. The old version required // you to "know" and "think" when writing asynch tests, and the // assert methods had not been available directly when writing // asynchronous tests, you had to use doh.callback/errback. // This allows to ONLY use assert*() methods. See the selftests // for examples. var myT = new function(){ this._assertClosure = function(method, args){ // If the Deferred instance is already "done", means callback or errback // had already been called dont do it again. // This might be the case when e.g. the test timed out. if (d.fired > -1){ return; } try{ var ret = doh.assert[method].apply(doh, args); d.callback(ret || true); }catch(e){ d.errback(e); } }; for (var methodName in doh.assert){ if (methodName.indexOf("assert")===0){ this[methodName] = (function(methodName){return function(){ this._assertClosure(methodName, arguments); }})(methodName); } } }; return myT; }, _makeNextTestCurrent:function(){ var c = this._current; // Is there a test left in this group? if (c.group && c.testIndex < c.group.tests.length-1){ c.testIndex++; } else { // First test in the next group, if there is another group. if (c.groupIndex < this._groups.length-1){ c.groupIndex++; c.group = this._groups[c.groupIndex]; doh.util.mixin(c.group, this._additionalGroupProperties); this.ui.groupStarted(c.group); c.testIndex = 0; } else { this.ui.report(); return false; } } c.test = c.group.tests[c.testIndex]; return true; }, _runNextTest:function(){ // summary: Only called from internally after a test has finished. if (this._isPaused){ return; } if (this._makeNextTestCurrent()){ this._runTest(); } }, _runTest:function(){ // summary: This executes the current test. // description: This method starts the "test" method of the test object // and finishes by setting the internal state "_testInFlight" to true, // which is resolved by the call to "_runNextTest()" which // automatically happens after the (asynchronous) test has "landed". var g = this._current.group, t = this._current.test; this.ui.testStarted(g, t); // let doh reference "this.group.thinger..." which can be set by // another test or group-level setUp function t.group = g; var deferred = new doh.Deferred(), assertWrapperObject = this._getAssertWrapper(deferred); if(t.setUp){ t.setUp(assertWrapperObject); } if(!t.test){ t.test = function(){deferred.errback(new Error("Test missing."));} } deferred.groupName = g.name; deferred.test = t; deferred.addErrback(function(err){ if (err instanceof doh.assert.Failure){ g.numFailures++; doh._numFailures++; doh.ui.testFailure(g, t, err); } else { g.numErrors++; doh._numErrors++; doh.ui.testError(g, t, err); } }); var retEnd = function(){ t.endTime = new Date(); g.numTestsExecuted++; doh._numTestsExecuted++; if(t.tearDown){ t.tearDown(assertWrapperObject); } doh.ui.testFinished(g, t, deferred.results[0]); // Is this the last test in the current group? var c = doh._current; if (c.testIndex == c.group.tests.length-1){ doh.ui.groupFinished(g); } } var timer = setTimeout(function(){ deferred.errback(new Error("test timeout in " + t.name.toString())); }, t.timeout || doh._defaultTimeout); - deferred.addBoth(doh.util.hitch(this, function(arg){ + deferred.addBoth(function(){ // Copy over the result if an asynchronous test has writte a result. // It must be available through the test object. // TODO maybe copy over all additional properties, compare to which props assertWrapperObject had upon creation and what new ones had been added, pass them all to t.* if (assertWrapperObject.result){ t.result = assertWrapperObject.result; } clearTimeout(timer); retEnd(); - this._testInFlight = false; - setTimeout(doh.util.hitch(this, "_runNextTest"), 1); - })); + doh._testInFlight = false; + setTimeout(doh.util.hitch(doh, "_runNextTest"), 1); + }); this._testInFlight = true; t.startTime = new Date(); t.result = t.test(assertWrapperObject); } }
wolframkriesing/doh2
1c8311525f9b984a726a45b761bf6cdda18a838c
+ better namespacing, added doh.assert.* and doh.util.* + properly separate errors and failures + added selftest for assertEqual on arrays
diff --git a/assert.js b/assert.js index d4818da..c155d35 100644 --- a/assert.js +++ b/assert.js @@ -1,163 +1,149 @@ -// -// Assertions and In-Test Utilities -// +doh.assert = { + assertTrue:function(/*Object*/ condition, /*String?*/ hint){ + // summary: + // is the passed item "truthy"? + if(arguments.length < 1){ + throw new doh.assert.Failure("assertTrue failed because it was not passed at least 1 argument"); + } + if(!eval(condition)){ + throw new doh.assert.Failure("assertTrue('" + condition + "') failed", hint); + } + }, -doh.t = doh.assertTrue = function(/*Object*/ condition, /*String?*/ hint){ - // summary: - // is the passed item "truthy"? - if(arguments.length < 1){ - throw new doh._AssertFailure("assertTrue failed because it was not passed at least 1 argument"); - } - if(!eval(condition)){ - throw new doh._AssertFailure("assertTrue('" + condition + "') failed", hint); - } -} + assertFalse:function(/*Object*/ condition, /*String?*/ hint){ + // summary: + // is the passed item "falsey"? + if(arguments.length < 1){ + throw new doh.assert.Failure("assertFalse failed because it was not passed at least 1 argument"); + } + if(eval(condition)){ + throw new doh.assert.Failure("assertFalse('" + condition + "') failed", hint); + } + }, -doh.f = doh.assertFalse = function(/*Object*/ condition, /*String?*/ hint){ - // summary: - // is the passed item "falsey"? - if(arguments.length < 1){ - throw new doh._AssertFailure("assertFalse failed because it was not passed at least 1 argument"); - } - if(eval(condition)){ - throw new doh._AssertFailure("assertFalse('" + condition + "') failed", hint); - } -} + assertError:function(/*Error object*/expectedError, /*Object*/scope, /*String*/functionName, /*Array*/args, /*String?*/ hint){ + // summary: + // Test for a certain error to be thrown by the given function. + // example: + // t.assertError(dojox.data.QueryReadStore.InvalidAttributeError, store, "getValue", [item, "NOT THERE"]); + // t.assertError(dojox.data.QueryReadStore.InvalidItemError, store, "getValue", ["not an item", "NOT THERE"]); + try{ + scope[functionName].apply(scope, args); + }catch (e){ + if(e instanceof expectedError){ + return true; + }else{ + throw new doh.assert.Failure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut got\n\t\t"+e+"\n\n", hint); + } + } + throw new doh.assert.Failure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut no error caught\n\n", hint); + }, -doh.e = doh.assertError = function(/*Error object*/expectedError, /*Object*/scope, /*String*/functionName, /*Array*/args, /*String?*/ hint){ - // summary: - // Test for a certain error to be thrown by the given function. - // example: - // t.assertError(dojox.data.QueryReadStore.InvalidAttributeError, store, "getValue", [item, "NOT THERE"]); - // t.assertError(dojox.data.QueryReadStore.InvalidItemError, store, "getValue", ["not an item", "NOT THERE"]); - try{ - scope[functionName].apply(scope, args); - }catch (e){ - if(e instanceof expectedError){ + assertEqual:function(/*Object*/ expected, /*Object*/ actual, /*String?*/ hint){ + // summary: + // are the passed expected and actual objects/values deeply + // equivalent? + + // Compare undefined always with three equal signs, because undefined==null + // is true, but undefined===null is false. + if((expected === undefined)&&(actual === undefined)){ return true; - }else{ - throw new doh._AssertFailure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut got\n\t\t"+e+"\n\n", hint); } - } - throw new doh._AssertFailure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut no error caught\n\n", hint); -} - - -doh.is = doh.assertEqual = function(/*Object*/ expected, /*Object*/ actual, /*String?*/ hint){ - // summary: - // are the passed expected and actual objects/values deeply - // equivalent? + if(arguments.length < 2){ + throw doh.assert.Failure("assertEqual failed because it was not passed 2 arguments"); + } + if((expected === actual)||(expected == actual)){ + return true; + } + if( (doh.util.isArray(expected) && doh.util.isArray(actual))&& + (doh.assert._arrayEq(expected, actual)) ){ + return true; + } + if( ((typeof expected == "object")&&((typeof actual == "object")))&& + (doh.assert._objPropEq(expected, actual)) ){ + return true; + } + throw new doh.assert.Failure("assertEqual() failed:\n\texpected\n\t\t"+expected+"\n\tbut got\n\t\t"+actual+"\n\n", hint); + }, - // Compare undefined always with three equal signs, because undefined==null - // is true, but undefined===null is false. - if((expected === undefined)&&(actual === undefined)){ - return true; - } - if(arguments.length < 2){ - throw doh._AssertFailure("assertEqual failed because it was not passed 2 arguments"); - } - if((expected === actual)||(expected == actual)){ - return true; - } - if( (this._isArray(expected) && this._isArray(actual))&& - (this._arrayEq(expected, actual)) ){ - return true; - } - if( ((typeof expected == "object")&&((typeof actual == "object")))&& - (this._objPropEq(expected, actual)) ){ + assertNotEqual:function(/*Object*/ notExpected, /*Object*/ actual, /*String?*/ hint){ + // summary: + // are the passed notexpected and actual objects/values deeply + // not equivalent? + + // Compare undefined always with three equal signs, because undefined==null + // is true, but undefined===null is false. + if((notExpected === undefined)&&(actual === undefined)){ + throw new doh.assert.Failure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); + } + if(arguments.length < 2){ + throw doh.assert.Failure("assertEqual failed because it was not passed 2 arguments"); + } + if((notExpected === actual)||(notExpected == actual)){ + throw new doh.assert.Failure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); + } + if( (doh.util.isArray(notExpected) && doh.util.isArray(actual))&& + (doh.assert._arrayEq(notExpected, actual)) ){ + throw new doh.assert.Failure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); + } + if( ((typeof notExpected == "object")&&((typeof actual == "object")))&& + (doh.assert._objPropEq(notExpected, actual)) ){ + throw new doh.assert.Failure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); + } return true; - } - throw new doh._AssertFailure("assertEqual() failed:\n\texpected\n\t\t"+expected+"\n\tbut got\n\t\t"+actual+"\n\n", hint); -} - -doh.isNot = doh.assertNotEqual = function(/*Object*/ notExpected, /*Object*/ actual, /*String?*/ hint){ - // summary: - // are the passed notexpected and actual objects/values deeply - // not equivalent? + }, - // Compare undefined always with three equal signs, because undefined==null - // is true, but undefined===null is false. - if((notExpected === undefined)&&(actual === undefined)){ - throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); - } - if(arguments.length < 2){ - throw doh._AssertFailure("assertEqual failed because it was not passed 2 arguments"); - } - if((notExpected === actual)||(notExpected == actual)){ - throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); - } - if( (this._isArray(notExpected) && this._isArray(actual))&& - (this._arrayEq(notExpected, actual)) ){ - throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); - } - if( ((typeof notExpected == "object")&&((typeof actual == "object")))&& - (this._objPropEq(notExpected, actual)) ){ - throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); - } - return true; -} - -doh._arrayEq = function(expected, actual){ - if(expected.length != actual.length){ return false; } - // FIXME: we're not handling circular refs. Do we care? - for(var x=0; x<expected.length; x++){ - if(!doh.assertEqual(expected[x], actual[x])){ return false; } - } - return true; -} - -doh._objPropEq = function(expected, actual){ - // Degenerate case: if they are both null, then their "properties" are equal. - if(expected === null && actual === null){ - return true; - } - // If only one is null, they aren't equal. - if(expected === null || actual === null){ - return false; - } - if(expected instanceof Date){ - return actual instanceof Date && expected.getTime()==actual.getTime(); - } - var x; - // Make sure ALL THE SAME properties are in both objects! - for(x in actual){ // Lets check "actual" here, expected is checked below. - if(expected[x] === undefined){ - return false; + _arrayEq:function(expected, actual){ + if(expected.length != actual.length){ return false; } + // FIXME: we're not handling circular refs. Do we care? + for(var x=0; x<expected.length; x++){ + if(!doh.assert.assertEqual(expected[x], actual[x])){ return false; } } - }; + return true; + }, - for(x in expected){ - if(!doh.assertEqual(expected[x], actual[x])){ + _objPropEq:function(expected, actual){ + // Degenerate case: if they are both null, then their "properties" are equal. + if(expected === null && actual === null){ + return true; + } + // If only one is null, they aren't equal. + if(expected === null || actual === null){ return false; } - } - return true; -} - -doh._isArray = function(it){ - return (it && it instanceof Array || typeof it == "array" || - ( - !!doh.global["dojo"] && - doh.global["dojo"]["NodeList"] !== undefined && - it instanceof doh.global["dojo"]["NodeList"] - ) - ); -} - - -doh._AssertFailure = function(msg, hint){ - // idea for this as way of dis-ambiguating error types is from JUM. - // The JUM is dead! Long live the JUM! + if(expected instanceof Date){ + return actual instanceof Date && expected.getTime()==actual.getTime(); + } + var x; + // Make sure ALL THE SAME properties are in both objects! + for(x in actual){ // Lets check "actual" here, expected is checked below. + if(expected[x] === undefined){ + return false; + } + }; + + for(x in expected){ + if(!doh.assert.assertEqual(expected[x], actual[x])){ + return false; + } + } + return true; + }, - if(!(this instanceof doh._AssertFailure)){ - return new doh._AssertFailure(msg); - } - if(hint){ - msg = (new String(msg||""))+" with hint: \n\t\t"+(new String(hint)+"\n"); + Failure:function(msg, hint){ + // idea for this as way of dis-ambiguating error types is from JUM. + // The JUM is dead! Long live the JUM! + + if(!(this instanceof doh.assert.Failure)){ + return new doh.assert.Failure(msg); + } + if(hint){ + msg = (new String(msg||""))+" with hint: \n\t\t"+(new String(hint)+"\n"); + } + this.message = new String(msg||""); + return this; } - this.message = new String(msg||""); - return this; -} -doh._AssertFailure.prototype = new Error(); -doh._AssertFailure.prototype.constructor = doh._AssertFailure; -doh._AssertFailure.prototype.name = "doh._AssertFailure"; +}; +doh.assert.Failure.prototype = new Error(); +doh.assert.Failure.prototype.constructor = doh.assert.Failure; +doh.assert.Failure.prototype.name = "doh.assert.Failure"; diff --git a/deferred.js b/deferred.js index 548daff..2521e71 100644 --- a/deferred.js +++ b/deferred.js @@ -1,189 +1,189 @@ doh.Deferred = function(canceller){ this.chain = []; this.id = this._nextId(); this.fired = -1; this.paused = 0; this.results = [null, null]; this.canceller = canceller; this.silentlyCancelled = false; }; -doh.extend(doh.Deferred, { +doh.util.extend(doh.Deferred, { getTestErrback: function(cb, scope){ // summary: Replaces outer getTextCallback's in nested situations to avoid multiple callback(true)'s var _this = this; return function(){ try{ - cb.apply(scope||doh.global||_this, arguments); + cb.apply(scope||doh.util.global||_this, arguments); }catch(e){ _this.errback(e); } }; }, getTestCallback: function(cb, scope){ var _this = this; return function(){ try{ - cb.apply(scope||doh.global||_this, arguments); + cb.apply(scope||doh.util.global||_this, arguments); }catch(e){ _this.errback(e); return; } _this.callback(true); }; }, getFunctionFromArgs: function(){ var a = arguments; if((a[0])&&(!a[1])){ if(typeof a[0] == "function"){ return a[0]; }else if(typeof a[0] == "string"){ - return doh.global[a[0]]; + return doh.util.global[a[0]]; } }else if((a[0])&&(a[1])){ - return doh.hitch(a[0], a[1]); + return doh.util.hitch(a[0], a[1]); } return null; }, makeCalled: function() { var deferred = new doh.Deferred(); deferred.callback(); return deferred; }, _nextId: (function(){ var n = 1; return function(){ return n++; }; })(), cancel: function(){ if(this.fired == -1){ if (this.canceller){ this.canceller(this); }else{ this.silentlyCancelled = true; } if(this.fired == -1){ this.errback(new Error("Deferred(unfired)")); } }else if(this.fired == 0 && (this.results[0] instanceof doh.Deferred)){ this.results[0].cancel(); } }, _pause: function(){ this.paused++; }, _unpause: function(){ this.paused--; if ((this.paused == 0) && (this.fired >= 0)) { this._fire(); } }, _continue: function(res){ this._resback(res); this._unpause(); }, _resback: function(res){ this.fired = ((res instanceof Error) ? 1 : 0); this.results[this.fired] = res; this._fire(); }, _check: function(){ if(this.fired != -1){ if(!this.silentlyCancelled){ throw new Error("already called!"); } this.silentlyCancelled = false; return; } }, callback: function(res){ this._check(); this._resback(res); }, errback: function(res){ this._check(); if(!(res instanceof Error)){ res = new Error(res); } this._resback(res); }, addBoth: function(cb, cbfn){ var enclosed = this.getFunctionFromArgs(cb, cbfn); if(arguments.length > 2){ - enclosed = doh.hitch(null, enclosed, arguments, 2); + enclosed = doh.util.hitch(null, enclosed, arguments, 2); } return this.addCallbacks(enclosed, enclosed); }, addCallback: function(cb, cbfn){ var enclosed = this.getFunctionFromArgs(cb, cbfn); if(arguments.length > 2){ - enclosed = doh.hitch(null, enclosed, arguments, 2); + enclosed = doh.util.hitch(null, enclosed, arguments, 2); } return this.addCallbacks(enclosed, null); }, addErrback: function(cb, cbfn){ var enclosed = this.getFunctionFromArgs(cb, cbfn); if(arguments.length > 2){ - enclosed = doh.hitch(null, enclosed, arguments, 2); + enclosed = doh.util.hitch(null, enclosed, arguments, 2); } return this.addCallbacks(null, enclosed); }, addCallbacks: function(cb, eb){ this.chain.push([cb, eb]); if(this.fired >= 0){ this._fire(); } return this; }, _fire: function(){ var chain = this.chain; var fired = this.fired; var res = this.results[fired]; var self = this; var cb = null; while(chain.length > 0 && this.paused == 0){ // Array var pair = chain.shift(); var f = pair[fired]; if(f == null){ continue; } try { res = f(res); fired = ((res instanceof Error) ? 1 : 0); if(res instanceof doh.Deferred){ cb = function(res){ self._continue(res); }; this._pause(); } }catch(err){ fired = 1; res = err; } } this.fired = fired; this.results[fired] = res; if((cb)&&(this.paused)){ res.addBoth(cb); } } }); diff --git a/doh.js b/doh.js index 51d3474..fcf8a72 100644 --- a/doh.js +++ b/doh.js @@ -1,209 +1,214 @@ doh = { // This is a temporary structure which points to the current data. _current:{ group:null, groupIndex:-1, test:null, testIndex:-1 }, // A helper property, which stores a reference to a test group by name. _groupsByName:{}, // Statistical data. _numTests:0, // The total number of tests. _numTestsExecuted:0, // Number of tests already executed. // Stats about the test results. _numErrors:0, _numFailures:0, // _isPaused:false, _defaultTimeout:1000, _testInFlight:false, // The groups must be an array, since an object does not necessarily maintain // it's order, but tests should be executed in the order as added. // This might become even more important when test dependencies will be added, // which means only execute test2 if test1 succeeded. _groups:[], _additionalGroupProperties:{ numTestsExecuted:0, numFailures:0, numErrors:0 }, pause:function(){ this._isPaused = true; }, register:function(groupName, tests){ // summary: Register the given tests to the group with the given name. // description: The tests are internally stored in "_groups", an array // which contains all the tests per group. The new tests are added // to the group with the given name, if it didnt exist yet it is created. var group = null; if (this._groupsByName[groupName]){ group = this._groupsByName[groupName]; } else { this._groups.push({name:groupName, tests:[]}); group = this._groupsByName[groupName] = this._groups[this._groups.length-1]; } for (var i=0, l=tests.length, t; i<l; i++){ t = {}; - doh.mixin(t, tests[i]); - //t.test = doh.hitch(this, "_makeDeferred", [t.test]); + doh.util.mixin(t, tests[i]); group.tests.push(t); } this._numTests += tests.length; }, run:function(){ if (this._current.group===null){ this.ui.started(); } this._isPaused = false; if (this._testInFlight){ return; } if (this._makeNextTestCurrent()){ this._runTest(); } }, _getAssertWrapper:function(d){ // summary: This returns an object which provides all the assert methods, and wraps a Deferred instance. // description: Why that? The interface for doh tests should be the same // for synchronous and asynchronous tests. The old version required // you to "know" and "think" when writing asynch tests, and the // assert methods had not been available directly when writing // asynchronous tests, you had to use doh.callback/errback. // This allows to ONLY use assert*() methods. See the selftests // for examples. var myT = new function(){ this._assertClosure = function(method, args){ // If the Deferred instance is already "done", means callback or errback // had already been called dont do it again. // This might be the case when e.g. the test timed out. if (d.fired > -1){ return; } try{ - var ret = doh[method].apply(doh, args); + var ret = doh.assert[method].apply(doh, args); d.callback(ret || true); }catch(e){ d.errback(e); } }; - for (var methodName in doh){ + for (var methodName in doh.assert){ if (methodName.indexOf("assert")===0){ this[methodName] = (function(methodName){return function(){ this._assertClosure(methodName, arguments); }})(methodName); } } }; return myT; }, _makeNextTestCurrent:function(){ var c = this._current; // Is there a test left in this group? if (c.group && c.testIndex < c.group.tests.length-1){ c.testIndex++; } else { // First test in the next group, if there is another group. if (c.groupIndex < this._groups.length-1){ c.groupIndex++; c.group = this._groups[c.groupIndex]; - doh.mixin(c.group, this._additionalGroupProperties); + doh.util.mixin(c.group, this._additionalGroupProperties); this.ui.groupStarted(c.group); c.testIndex = 0; } else { this.ui.report(); return false; } } c.test = c.group.tests[c.testIndex]; return true; }, _runNextTest:function(){ // summary: Only called from internally after a test has finished. if (this._isPaused){ return; } if (this._makeNextTestCurrent()){ this._runTest(); } }, _runTest:function(){ // summary: This executes the current test. // description: This method starts the "test" method of the test object // and finishes by setting the internal state "_testInFlight" to true, // which is resolved by the call to "_runNextTest()" which // automatically happens after the (asynchronous) test has "landed". var g = this._current.group, t = this._current.test; this.ui.testStarted(g, t); // let doh reference "this.group.thinger..." which can be set by // another test or group-level setUp function t.group = g; var deferred = new doh.Deferred(), assertWrapperObject = this._getAssertWrapper(deferred); if(t.setUp){ t.setUp(assertWrapperObject); } if(!t.test){ t.test = function(){deferred.errback(new Error("Test missing."));} } deferred.groupName = g.name; deferred.test = t; deferred.addErrback(function(err){ - g.numFailures++; - doh._numFailures++; - doh.ui.testFailed(g, t, err); + if (err instanceof doh.assert.Failure){ + g.numFailures++; + doh._numFailures++; + doh.ui.testFailure(g, t, err); + } else { + g.numErrors++; + doh._numErrors++; + doh.ui.testError(g, t, err); + } }); var retEnd = function(){ t.endTime = new Date(); g.numTestsExecuted++; doh._numTestsExecuted++; if(t.tearDown){ t.tearDown(assertWrapperObject); } doh.ui.testFinished(g, t, deferred.results[0]); // Is this the last test in the current group? var c = doh._current; if (c.testIndex == c.group.tests.length-1){ doh.ui.groupFinished(g); } } var timer = setTimeout(function(){ deferred.errback(new Error("test timeout in " + t.name.toString())); }, t.timeout || doh._defaultTimeout); - deferred.addBoth(doh.hitch(this, function(arg){ + deferred.addBoth(doh.util.hitch(this, function(arg){ // Copy over the result if an asynchronous test has writte a result. // It must be available through the test object. // TODO maybe copy over all additional properties, compare to which props assertWrapperObject had upon creation and what new ones had been added, pass them all to t.* if (assertWrapperObject.result){ t.result = assertWrapperObject.result; } clearTimeout(timer); retEnd(); this._testInFlight = false; - setTimeout(doh.hitch(this, "_runNextTest"), 1); + setTimeout(doh.util.hitch(this, "_runNextTest"), 1); })); this._testInFlight = true; t.startTime = new Date(); t.result = t.test(assertWrapperObject); } } diff --git a/selftests.js b/selftests.js index 831358c..4c6002a 100644 --- a/selftests.js +++ b/selftests.js @@ -1,136 +1,147 @@ doh.register("Synchronously written tests.", [ // // assertTrue // { name:"fail: assertTrue", test:function(t){ t.assertTrue(false); } },{ name:"success: assertTrue", test:function(t){ t.assertTrue(true); } }, // // assertFalse // { name:"fail: assertFalse", test:function(t){ t.assertFalse(true); } },{ name:"success: assertFalse", test:function(t){ t.assertFalse(false); } }, // // assertEqual // { name:"fail: assertEqual bools", test:function(t){ t.assertEqual(true, false); } },{ name:"success: assertFalse bools", test:function(t){ t.assertEqual(true, true); } }, { name:"fail: assertEqual numbers", test:function(t){ t.assertEqual(1, "2"); } },{ - name:"success: assertFalse numbers", + name:"success: assertEqual numbers", test:function(t){ t.assertEqual(1, "1"); } }, + { + name:"fail: assertEqual arrays", + test:function(t){ + t.assertEqual([1,2], [2,1]); + } + },{ + name:"success: assertEqual arrays", + test:function(t){ + t.assertEqual([2,3], [2,3]); + } + }, { // A missing assert call. - name:"fail: timeout, assert() missing", + name:"error: timeout, assert() missing", test:function(t){ } },{ // This test will fail, because it has no implementation of the test method. - name:"fail: test() missing" + name:"error: test() missing" } ] ); doh.register("Asynchronous tests.", [ { // Inside of an asynch test case you can (and should) still use the assert() methods. // No return necessary anymore!!! name:"fail: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(false); }, 1000); } }, { name:"success: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, { - name:"fail: timeout", + name:"error: timeout", timeout:100, // This timeout is shorter than the setTimeout below, this test should fail. test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, ] ); var timeDiff; doh.register("Test doh.pause()", [ { // Test that calling pause() from inside a test does pause the test // suite and do also test that run() does continue. name:"success: pause after this test (and run again)", test:function(t){ t.assertTrue(true); doh.pause(); timeDiff = new Date().getTime(); setTimeout(function(){doh.run()}, 3500); } }, { // This test basically measures the time that the test before had // paused the test execution and it should be between 3-4 secs. name:"success: measure paused time", test:function(t){ var diff = new Date().getTime() - timeDiff t.assertTrue(diff > 3000 && diff < 4000, "The pause should be between 3-4 seconds."); } }, ] ); \ No newline at end of file diff --git a/ui.js b/ui.js index 5ab2265..40d8991 100644 --- a/ui.js +++ b/ui.js @@ -1,39 +1,49 @@ doh.ui = { + // summary: This object contains the functions that are responsible for rendering out the results of each test. + // description: Override this object or the funtion(s) you need to override. started:function(){ // summary: This is called when run() was called the first time. console.log(doh._numTests + " tests registered, in " + doh._groups.length + " groups"); console.log("--------"); }, - - testRegistered:function(group, test){ - }, groupStarted:function(group){ + // summary: Called before a group's tests get executed. console.log("Starting group '" + group.name + "', " + group.tests.length + " tests"); }, groupFinished:function(group){ + // summary: After all group's tests ran. console.log(group.numTestsExecuted + " tests ran, " + group.numFailures + " failures, " + group.numErrors + " errors"); console.log("--------"); }, - + testStarted:function(group, test){ + // summary: Before a test's test() method is executed. }, - - testFailed:function(group, test, error){ - console.log(test.name + " FAILED, " + error.message); + + testFailure:function(group, test, error){ + // summary: After a test failed. + console.log(test.name + " FAILURE, " + error.message); }, - + + testError:function(group, test, error){ + // summary: After a test failed. + console.log(test.name + " ERROR, " + error.message); + }, + testFinished:function(group, test, success){ + // summary: }, report:function(){ + // summary: console.log(doh._numTestsExecuted + " tests ran, " + doh._numFailures + " failures, " + doh._numErrors + " errors"); console.log("========"); } } \ No newline at end of file diff --git a/util.js b/util.js index 417c34d..d4954b6 100644 --- a/util.js +++ b/util.js @@ -1,77 +1,74 @@ -// package system gunk. e -try{ - dojo.provide("doh.runner"); -}catch(e){ - if(!this["doh"]){ - doh = {}; - } -} - -// -// Utility Functions and Classes -// - -doh.selfTest = false; - -doh.global = this; +doh.util = { + hitch:function(/*Object*/thisObject, /*Function|String*/method /*, ...*/){ + var args = []; + for(var x=2; x<arguments.length; x++){ + args.push(arguments[x]); + } + var fcn = ((typeof method == "string") ? thisObject[method] : method) || function(){}; + return function(){ + var ta = args.concat([]); // make a copy + for(var x=0; x<arguments.length; x++){ + ta.push(arguments[x]); + } + return fcn.apply(thisObject, ta); // Function + }; + }, -doh.hitch = function(/*Object*/thisObject, /*Function|String*/method /*, ...*/){ - var args = []; - for(var x=2; x<arguments.length; x++){ - args.push(arguments[x]); - } - var fcn = ((typeof method == "string") ? thisObject[method] : method) || function(){}; - return function(){ - var ta = args.concat([]); // make a copy - for(var x=0; x<arguments.length; x++){ - ta.push(arguments[x]); + _mixin:function(/*Object*/ obj, /*Object*/ props){ + // summary: + // Adds all properties and methods of props to obj. This addition is + // "prototype extension safe", so that instances of objects will not + // pass along prototype defaults. + var tobj = {}; + for(var x in props){ + // the "tobj" condition avoid copying properties in "props" + // inherited from Object.prototype. For example, if obj has a custom + // toString() method, don't overwrite it with the toString() method + // that props inherited from Object.protoype + if(tobj[x] === undefined || tobj[x] != props[x]){ + obj[x] = props[x]; + } } - return fcn.apply(thisObject, ta); // Function - }; -} + // IE doesn't recognize custom toStrings in for..in + if( this["document"] + && document.all + && (typeof props["toString"] == "function") + && (props["toString"] != obj["toString"]) + && (props["toString"] != tobj["toString"]) + ){ + obj.toString = props.toString; + } + return obj; // Object + }, -doh._mixin = function(/*Object*/ obj, /*Object*/ props){ - // summary: - // Adds all properties and methods of props to obj. This addition is - // "prototype extension safe", so that instances of objects will not - // pass along prototype defaults. - var tobj = {}; - for(var x in props){ - // the "tobj" condition avoid copying properties in "props" - // inherited from Object.prototype. For example, if obj has a custom - // toString() method, don't overwrite it with the toString() method - // that props inherited from Object.protoype - if(tobj[x] === undefined || tobj[x] != props[x]){ - obj[x] = props[x]; + mixin:function(/*Object*/obj, /*Object...*/props){ + // summary: Adds all properties and methods of props to obj. + for(var i=1, l=arguments.length; i<l; i++){ + this._mixin(obj, arguments[i]); } - } - // IE doesn't recognize custom toStrings in for..in - if( this["document"] - && document.all - && (typeof props["toString"] == "function") - && (props["toString"] != obj["toString"]) - && (props["toString"] != tobj["toString"]) - ){ - obj.toString = props.toString; - } - return obj; // Object -} + return obj; // Object + }, -doh.mixin = function(/*Object*/obj, /*Object...*/props){ - // summary: Adds all properties and methods of props to obj. - for(var i=1, l=arguments.length; i<l; i++){ - doh._mixin(obj, arguments[i]); + extend:function(/*Object*/ constructor, /*Object...*/ props){ + // summary: + // Adds all properties and methods of props to constructor's + // prototype, making them available to all instances created with + // constructor. + for(var i=1, l=arguments.length; i<l; i++){ + this._mixin(constructor.prototype, arguments[i]); + } + return constructor; // Object + }, + + isArray:function(it){ + return (it && it instanceof Array || typeof it == "array" || + ( + !!doh.util.global["dojo"] && + doh.util.global["dojo"]["NodeList"] !== undefined && + it instanceof doh.util.global["dojo"]["NodeList"] + ) + ); } - return obj; // Object -} +}; -doh.extend = function(/*Object*/ constructor, /*Object...*/ props){ - // summary: - // Adds all properties and methods of props to constructor's - // prototype, making them available to all instances created with - // constructor. - for(var i=1, l=arguments.length; i<l; i++){ - doh._mixin(constructor.prototype, arguments[i]); - } - return constructor; // Object -} +doh.util.global = this;
wolframkriesing/doh2
a1e1e5897c0906448f188d99936821a462f05716
+ added some more selftests
diff --git a/selftest.html b/selftest.html new file mode 100644 index 0000000..0ea6292 --- /dev/null +++ b/selftest.html @@ -0,0 +1,48 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> + <title>D.O.H. v2</title> + <meta http-equiv="content-type" content="text/html; charset=utf-8"> +</head> +<body> + + <h1>Self tests</h1> + <p>This will run several tests using this library, don't be scared when some + of the test fail, this is intentionally, to test the test suite itself.</p> + + <h2>Your result should look like this:</h2> + <pre style="font-size: large; color: red;"> +<span id="numTestsRan">0</span> tests ran, <span id="numFailures">0</span> failures, <span id="numErrors">0</span> errors + </pre> + + <script type="text/javascript" src="doh.js"></script> + <script type="text/javascript" src="util.js"></script> + <script type="text/javascript" src="deferred.js"></script> + <script type="text/javascript" src="assert.js"></script> + <script type="text/javascript" src="ui.js"></script> + <script type="text/javascript" src="selftests.js"></script> + <script type="text/javascript"> + // Go through all the tests and find out how many should fail + // and how many should pass, the name of each test tells. + // And fill the HTML above appropriately. + var numTests = 0, + numFailures = 0, + numErrors = 0; + for (var i=0, g; g=doh._groups[i]; i++){ + numTests += g.tests.length; + for (var j=0, t; t=g.tests[j]; j++){ + if (t.name.indexOf("fail: ")===0){ + numFailures++; + } else if (t.name.indexOf("error: ")===0){ + numErrors++; + } + } + } + document.getElementById("numTestsRan").innerHTML = numTests; + document.getElementById("numFailures").innerHTML = numFailures; + document.getElementById("numErrors").innerHTML = numErrors; + + doh.run(); + </script> +</body> +</html>
wolframkriesing/doh2
a791aade6b4c01ba88ea1d15d6435f0fe74bbbe8
+ added some more selftests
diff --git a/index.html b/index.html deleted file mode 100644 index 48b971f..0000000 --- a/index.html +++ /dev/null @@ -1,18 +0,0 @@ -<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> -<html> -<head> - <title>D.O.H. v2</title> - <meta http-equiv="content-type" content="text/html; charset=utf-8"> -</head> -<body> - <script type="text/javascript" src="doh.js"></script> - <script type="text/javascript" src="util.js"></script> - <script type="text/javascript" src="deferred.js"></script> - <script type="text/javascript" src="assert.js"></script> - <script type="text/javascript" src="ui.js"></script> - <script type="text/javascript" src="selftests.js"></script> - <script type="text/javascript"> - doh.run(); - </script> -</body> -</html> diff --git a/selftests.js b/selftests.js index 80aea69..831358c 100644 --- a/selftests.js +++ b/selftests.js @@ -1,69 +1,136 @@ doh.register("Synchronously written tests.", [ + // + // assertTrue + // { - name:"fail: simple assertTrue", + name:"fail: assertTrue", test:function(t){ t.assertTrue(false); } },{ - name:"success: simple assertTrue", + name:"success: assertTrue", test:function(t){ t.assertTrue(true); } + }, + // + // assertFalse + // + { + name:"fail: assertFalse", + test:function(t){ + t.assertFalse(true); + } + },{ + name:"success: assertFalse", + test:function(t){ + t.assertFalse(false); + } + }, + // + // assertEqual + // + { + name:"fail: assertEqual bools", + test:function(t){ + t.assertEqual(true, false); + } + },{ + name:"success: assertFalse bools", + test:function(t){ + t.assertEqual(true, true); + } + }, + { + name:"fail: assertEqual numbers", + test:function(t){ + t.assertEqual(1, "2"); + } },{ + name:"success: assertFalse numbers", + test:function(t){ + t.assertEqual(1, "1"); + } + }, + + + + + + + + + + { + // A missing assert call. name:"fail: timeout, assert() missing", test:function(t){ } },{ // This test will fail, because it has no implementation of the test method. name:"fail: test() missing" } ] ); doh.register("Asynchronous tests.", [ { // Inside of an asynch test case you can (and should) still use the assert() methods. // No return necessary anymore!!! name:"fail: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(false); }, 1000); } }, { name:"success: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, { name:"fail: timeout", timeout:100, // This timeout is shorter than the setTimeout below, this test should fail. test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, ] ); -doh.register("Other features.", +var timeDiff; +doh.register("Test doh.pause()", [ { - name:"success: pause after this test", + // Test that calling pause() from inside a test does pause the test + // suite and do also test that run() does continue. + name:"success: pause after this test (and run again)", test:function(t){ t.assertTrue(true); - //doh.pause(); + doh.pause(); + timeDiff = new Date().getTime(); + setTimeout(function(){doh.run()}, 3500); + } + }, + { + // This test basically measures the time that the test before had + // paused the test execution and it should be between 3-4 secs. + name:"success: measure paused time", + test:function(t){ + var diff = new Date().getTime() - timeDiff + t.assertTrue(diff > 3000 && diff < 4000, "The pause should be between 3-4 seconds."); } }, ] ); \ No newline at end of file diff --git a/ui.js b/ui.js index d0eb4a6..5ab2265 100644 --- a/ui.js +++ b/ui.js @@ -1,39 +1,39 @@ doh.ui = { started:function(){ // summary: This is called when run() was called the first time. console.log(doh._numTests + " tests registered, in " + doh._groups.length + " groups"); console.log("--------"); }, testRegistered:function(group, test){ }, groupStarted:function(group){ console.log("Starting group '" + group.name + "', " + group.tests.length + " tests"); }, groupFinished:function(group){ console.log(group.numTestsExecuted + " tests ran, " + group.numFailures + " failures, " + group.numErrors + " errors"); console.log("--------"); }, testStarted:function(group, test){ }, testFailed:function(group, test, error){ - console.log(test.name + " FAILED, " + error); + console.log(test.name + " FAILED, " + error.message); }, testFinished:function(group, test, success){ }, report:function(){ console.log(doh._numTestsExecuted + " tests ran, " + doh._numFailures + " failures, " + doh._numErrors + " errors"); console.log("========"); } } \ No newline at end of file
wolframkriesing/doh2
ff7d16118d392d976f5cce2895df85395c38bca5
+ made it work
diff --git a/doh.js b/doh.js index 9f6604b..51d3474 100644 --- a/doh.js +++ b/doh.js @@ -1,218 +1,209 @@ doh = { // This is a temporary structure which points to the current data. _current:{ group:null, groupIndex:-1, test:null, testIndex:-1 }, // A helper property, which stores a reference to a test group by name. _groupsByName:{}, // Statistical data. _numTests:0, // The total number of tests. _numTestsExecuted:0, // Number of tests already executed. // Stats about the test results. _numErrors:0, _numFailures:0, // _isPaused:false, _defaultTimeout:1000, _testInFlight:false, // The groups must be an array, since an object does not necessarily maintain // it's order, but tests should be executed in the order as added. // This might become even more important when test dependencies will be added, // which means only execute test2 if test1 succeeded. _groups:[], + _additionalGroupProperties:{ + numTestsExecuted:0, + numFailures:0, + numErrors:0 + }, + pause:function(){ this._isPaused = true; }, register:function(groupName, tests){ // summary: Register the given tests to the group with the given name. // description: The tests are internally stored in "_groups", an array // which contains all the tests per group. The new tests are added // to the group with the given name, if it didnt exist yet it is created. var group = null; if (this._groupsByName[groupName]){ group = this._groupsByName[groupName]; } else { this._groups.push({name:groupName, tests:[]}); group = this._groupsByName[groupName] = this._groups[this._groups.length-1]; } for (var i=0, l=tests.length, t; i<l; i++){ t = {}; doh.mixin(t, tests[i]); //t.test = doh.hitch(this, "_makeDeferred", [t.test]); group.tests.push(t); } + this._numTests += tests.length; }, run:function(){ + if (this._current.group===null){ + this.ui.started(); + } this._isPaused = false; if (this._testInFlight){ return; } if (this._makeNextTestCurrent()){ this._runTest(); } }, _getAssertWrapper:function(d){ // summary: This returns an object which provides all the assert methods, and wraps a Deferred instance. // description: Why that? The interface for doh tests should be the same // for synchronous and asynchronous tests. The old version required // you to "know" and "think" when writing asynch tests, and the // assert methods had not been available directly when writing // asynchronous tests, you had to use doh.callback/errback. // This allows to ONLY use assert*() methods. See the selftests // for examples. var myT = new function(){ this._assertClosure = function(method, args){ // If the Deferred instance is already "done", means callback or errback // had already been called dont do it again. // This might be the case when e.g. the test timed out. if (d.fired > -1){ return; } try{ var ret = doh[method].apply(doh, args); d.callback(ret || true); }catch(e){ d.errback(e); } }; for (var methodName in doh){ if (methodName.indexOf("assert")===0){ this[methodName] = (function(methodName){return function(){ this._assertClosure(methodName, arguments); }})(methodName); } } }; return myT; }, _makeNextTestCurrent:function(){ var c = this._current; // Is there a test left in this group? if (c.group && c.testIndex < c.group.tests.length-1){ c.testIndex++; } else { // First test in the next group, if there is another group. if (c.groupIndex < this._groups.length-1){ c.groupIndex++; c.group = this._groups[c.groupIndex]; + doh.mixin(c.group, this._additionalGroupProperties); + this.ui.groupStarted(c.group); c.testIndex = 0; } else { + this.ui.report(); return false; } } c.test = c.group.tests[c.testIndex]; return true; }, - + _runNextTest:function(){ // summary: Only called from internally after a test has finished. if (this._isPaused){ return; } if (this._makeNextTestCurrent()){ this._runTest(); } }, _runTest:function(){ // summary: This executes the current test. // description: This method starts the "test" method of the test object // and finishes by setting the internal state "_testInFlight" to true, // which is resolved by the call to "_runNextTest()" which // automatically happens after the (asynchronous) test has "landed". var g = this._current.group, t = this._current.test; - this._testStarted(g, t); + this.ui.testStarted(g, t); // let doh reference "this.group.thinger..." which can be set by // another test or group-level setUp function t.group = g; var deferred = new doh.Deferred(), assertWrapperObject = this._getAssertWrapper(deferred); if(t.setUp){ t.setUp(assertWrapperObject); } if(!t.test){ t.test = function(){deferred.errback(new Error("Test missing."));} } deferred.groupName = g.name; deferred.test = t; deferred.addErrback(function(err){ - doh._handleFailure(g, t, err); + g.numFailures++; + doh._numFailures++; + doh.ui.testFailed(g, t, err); }); var retEnd = function(){ t.endTime = new Date(); + g.numTestsExecuted++; + doh._numTestsExecuted++; if(t.tearDown){ t.tearDown(assertWrapperObject); } - doh._testEnd(g, t, deferred.results[0]); + doh.ui.testFinished(g, t, deferred.results[0]); + // Is this the last test in the current group? + var c = doh._current; + if (c.testIndex == c.group.tests.length-1){ + doh.ui.groupFinished(g); + } } var timer = setTimeout(function(){ deferred.errback(new Error("test timeout in " + t.name.toString())); }, t.timeout || doh._defaultTimeout); deferred.addBoth(doh.hitch(this, function(arg){ + // Copy over the result if an asynchronous test has writte a result. + // It must be available through the test object. +// TODO maybe copy over all additional properties, compare to which props assertWrapperObject had upon creation and what new ones had been added, pass them all to t.* + if (assertWrapperObject.result){ + t.result = assertWrapperObject.result; + } clearTimeout(timer); retEnd(); this._testInFlight = false; setTimeout(doh.hitch(this, "_runNextTest"), 1); })); this._testInFlight = true; t.startTime = new Date(); - t.test(assertWrapperObject); + t.result = t.test(assertWrapperObject); } } - - - - -doh._testRegistered = function(group, fixture){ - // slot to be filled in -} - -doh._groupStarted = function(group){ - // slot to be filled in -} - -doh._groupFinished = function(group, success){ - // slot to be filled in -} - -doh._testStarted = function(group, fixture){ - // slot to be filled in -} - -doh._testFinished = function(group, fixture, success){ - // slot to be filled in -} - - - - - - -doh._testEnd = function(g, t, result){ - doh._currentTestCount++; - doh._testFinished(g, t, result); - if((!g.inFlight)&&(g.iterated)){ - doh._groupFinished(group.name, !g.failures); - } -} - diff --git a/index.html b/index.html index e69de29..48b971f 100644 --- a/index.html +++ b/index.html @@ -0,0 +1,18 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> +<html> +<head> + <title>D.O.H. v2</title> + <meta http-equiv="content-type" content="text/html; charset=utf-8"> +</head> +<body> + <script type="text/javascript" src="doh.js"></script> + <script type="text/javascript" src="util.js"></script> + <script type="text/javascript" src="deferred.js"></script> + <script type="text/javascript" src="assert.js"></script> + <script type="text/javascript" src="ui.js"></script> + <script type="text/javascript" src="selftests.js"></script> + <script type="text/javascript"> + doh.run(); + </script> +</body> +</html> diff --git a/selftests.js b/selftests.js index e5c3162..80aea69 100644 --- a/selftests.js +++ b/selftests.js @@ -1,69 +1,69 @@ doh.register("Synchronously written tests.", [ { name:"fail: simple assertTrue", test:function(t){ t.assertTrue(false); } },{ name:"success: simple assertTrue", test:function(t){ t.assertTrue(true); } },{ name:"fail: timeout, assert() missing", test:function(t){ } },{ // This test will fail, because it has no implementation of the test method. name:"fail: test() missing" } ] ); doh.register("Asynchronous tests.", [ { // Inside of an asynch test case you can (and should) still use the assert() methods. // No return necessary anymore!!! name:"fail: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(false); }, 1000); } }, { name:"success: simple asynch", timeout:2000, test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, { name:"fail: timeout", timeout:100, // This timeout is shorter than the setTimeout below, this test should fail. test:function(t){ setTimeout(function(){ t.assertTrue(true); }, 1000); } }, ] ); doh.register("Other features.", [ { name:"success: pause after this test", test:function(t){ t.assertTrue(true); - doh.pause(); + //doh.pause(); } }, ] ); \ No newline at end of file
wolframkriesing/doh2
e5612e5f286fe3b2006469f4f9d96fe3fc0ac76a
+ initial version, dumps to console
diff --git a/assert.js b/assert.js new file mode 100644 index 0000000..d4818da --- /dev/null +++ b/assert.js @@ -0,0 +1,163 @@ +// +// Assertions and In-Test Utilities +// + +doh.t = doh.assertTrue = function(/*Object*/ condition, /*String?*/ hint){ + // summary: + // is the passed item "truthy"? + if(arguments.length < 1){ + throw new doh._AssertFailure("assertTrue failed because it was not passed at least 1 argument"); + } + if(!eval(condition)){ + throw new doh._AssertFailure("assertTrue('" + condition + "') failed", hint); + } +} + +doh.f = doh.assertFalse = function(/*Object*/ condition, /*String?*/ hint){ + // summary: + // is the passed item "falsey"? + if(arguments.length < 1){ + throw new doh._AssertFailure("assertFalse failed because it was not passed at least 1 argument"); + } + if(eval(condition)){ + throw new doh._AssertFailure("assertFalse('" + condition + "') failed", hint); + } +} + +doh.e = doh.assertError = function(/*Error object*/expectedError, /*Object*/scope, /*String*/functionName, /*Array*/args, /*String?*/ hint){ + // summary: + // Test for a certain error to be thrown by the given function. + // example: + // t.assertError(dojox.data.QueryReadStore.InvalidAttributeError, store, "getValue", [item, "NOT THERE"]); + // t.assertError(dojox.data.QueryReadStore.InvalidItemError, store, "getValue", ["not an item", "NOT THERE"]); + try{ + scope[functionName].apply(scope, args); + }catch (e){ + if(e instanceof expectedError){ + return true; + }else{ + throw new doh._AssertFailure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut got\n\t\t"+e+"\n\n", hint); + } + } + throw new doh._AssertFailure("assertError() failed:\n\texpected error\n\t\t"+expectedError+"\n\tbut no error caught\n\n", hint); +} + + +doh.is = doh.assertEqual = function(/*Object*/ expected, /*Object*/ actual, /*String?*/ hint){ + // summary: + // are the passed expected and actual objects/values deeply + // equivalent? + + // Compare undefined always with three equal signs, because undefined==null + // is true, but undefined===null is false. + if((expected === undefined)&&(actual === undefined)){ + return true; + } + if(arguments.length < 2){ + throw doh._AssertFailure("assertEqual failed because it was not passed 2 arguments"); + } + if((expected === actual)||(expected == actual)){ + return true; + } + if( (this._isArray(expected) && this._isArray(actual))&& + (this._arrayEq(expected, actual)) ){ + return true; + } + if( ((typeof expected == "object")&&((typeof actual == "object")))&& + (this._objPropEq(expected, actual)) ){ + return true; + } + throw new doh._AssertFailure("assertEqual() failed:\n\texpected\n\t\t"+expected+"\n\tbut got\n\t\t"+actual+"\n\n", hint); +} + +doh.isNot = doh.assertNotEqual = function(/*Object*/ notExpected, /*Object*/ actual, /*String?*/ hint){ + // summary: + // are the passed notexpected and actual objects/values deeply + // not equivalent? + + // Compare undefined always with three equal signs, because undefined==null + // is true, but undefined===null is false. + if((notExpected === undefined)&&(actual === undefined)){ + throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); + } + if(arguments.length < 2){ + throw doh._AssertFailure("assertEqual failed because it was not passed 2 arguments"); + } + if((notExpected === actual)||(notExpected == actual)){ + throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); + } + if( (this._isArray(notExpected) && this._isArray(actual))&& + (this._arrayEq(notExpected, actual)) ){ + throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); + } + if( ((typeof notExpected == "object")&&((typeof actual == "object")))&& + (this._objPropEq(notExpected, actual)) ){ + throw new doh._AssertFailure("assertNotEqual() failed: not expected |"+notExpected+"| but got |"+actual+"|", hint); + } + return true; +} + +doh._arrayEq = function(expected, actual){ + if(expected.length != actual.length){ return false; } + // FIXME: we're not handling circular refs. Do we care? + for(var x=0; x<expected.length; x++){ + if(!doh.assertEqual(expected[x], actual[x])){ return false; } + } + return true; +} + +doh._objPropEq = function(expected, actual){ + // Degenerate case: if they are both null, then their "properties" are equal. + if(expected === null && actual === null){ + return true; + } + // If only one is null, they aren't equal. + if(expected === null || actual === null){ + return false; + } + if(expected instanceof Date){ + return actual instanceof Date && expected.getTime()==actual.getTime(); + } + var x; + // Make sure ALL THE SAME properties are in both objects! + for(x in actual){ // Lets check "actual" here, expected is checked below. + if(expected[x] === undefined){ + return false; + } + }; + + for(x in expected){ + if(!doh.assertEqual(expected[x], actual[x])){ + return false; + } + } + return true; +} + +doh._isArray = function(it){ + return (it && it instanceof Array || typeof it == "array" || + ( + !!doh.global["dojo"] && + doh.global["dojo"]["NodeList"] !== undefined && + it instanceof doh.global["dojo"]["NodeList"] + ) + ); +} + + +doh._AssertFailure = function(msg, hint){ + // idea for this as way of dis-ambiguating error types is from JUM. + // The JUM is dead! Long live the JUM! + + if(!(this instanceof doh._AssertFailure)){ + return new doh._AssertFailure(msg); + } + if(hint){ + msg = (new String(msg||""))+" with hint: \n\t\t"+(new String(hint)+"\n"); + } + this.message = new String(msg||""); + return this; +} +doh._AssertFailure.prototype = new Error(); +doh._AssertFailure.prototype.constructor = doh._AssertFailure; +doh._AssertFailure.prototype.name = "doh._AssertFailure"; diff --git a/deferred.js b/deferred.js new file mode 100644 index 0000000..548daff --- /dev/null +++ b/deferred.js @@ -0,0 +1,189 @@ +doh.Deferred = function(canceller){ + this.chain = []; + this.id = this._nextId(); + this.fired = -1; + this.paused = 0; + this.results = [null, null]; + this.canceller = canceller; + this.silentlyCancelled = false; +}; + +doh.extend(doh.Deferred, { + getTestErrback: function(cb, scope){ + // summary: Replaces outer getTextCallback's in nested situations to avoid multiple callback(true)'s + var _this = this; + return function(){ + try{ + cb.apply(scope||doh.global||_this, arguments); + }catch(e){ + _this.errback(e); + } + }; + }, + + getTestCallback: function(cb, scope){ + var _this = this; + return function(){ + try{ + cb.apply(scope||doh.global||_this, arguments); + }catch(e){ + _this.errback(e); + return; + } + _this.callback(true); + }; + }, + + getFunctionFromArgs: function(){ + var a = arguments; + if((a[0])&&(!a[1])){ + if(typeof a[0] == "function"){ + return a[0]; + }else if(typeof a[0] == "string"){ + return doh.global[a[0]]; + } + }else if((a[0])&&(a[1])){ + return doh.hitch(a[0], a[1]); + } + return null; + }, + + makeCalled: function() { + var deferred = new doh.Deferred(); + deferred.callback(); + return deferred; + }, + + _nextId: (function(){ + var n = 1; + return function(){ return n++; }; + })(), + + cancel: function(){ + if(this.fired == -1){ + if (this.canceller){ + this.canceller(this); + }else{ + this.silentlyCancelled = true; + } + if(this.fired == -1){ + this.errback(new Error("Deferred(unfired)")); + } + }else if(this.fired == 0 && + (this.results[0] instanceof doh.Deferred)){ + this.results[0].cancel(); + } + }, + + + _pause: function(){ + this.paused++; + }, + + _unpause: function(){ + this.paused--; + if ((this.paused == 0) && (this.fired >= 0)) { + this._fire(); + } + }, + + _continue: function(res){ + this._resback(res); + this._unpause(); + }, + + _resback: function(res){ + this.fired = ((res instanceof Error) ? 1 : 0); + this.results[this.fired] = res; + this._fire(); + }, + + _check: function(){ + if(this.fired != -1){ + if(!this.silentlyCancelled){ + throw new Error("already called!"); + } + this.silentlyCancelled = false; + return; + } + }, + + callback: function(res){ + this._check(); + this._resback(res); + }, + + errback: function(res){ + this._check(); + if(!(res instanceof Error)){ + res = new Error(res); + } + this._resback(res); + }, + + addBoth: function(cb, cbfn){ + var enclosed = this.getFunctionFromArgs(cb, cbfn); + if(arguments.length > 2){ + enclosed = doh.hitch(null, enclosed, arguments, 2); + } + return this.addCallbacks(enclosed, enclosed); + }, + + addCallback: function(cb, cbfn){ + var enclosed = this.getFunctionFromArgs(cb, cbfn); + if(arguments.length > 2){ + enclosed = doh.hitch(null, enclosed, arguments, 2); + } + return this.addCallbacks(enclosed, null); + }, + + addErrback: function(cb, cbfn){ + var enclosed = this.getFunctionFromArgs(cb, cbfn); + if(arguments.length > 2){ + enclosed = doh.hitch(null, enclosed, arguments, 2); + } + return this.addCallbacks(null, enclosed); + }, + + addCallbacks: function(cb, eb){ + this.chain.push([cb, eb]); + if(this.fired >= 0){ + this._fire(); + } + return this; + }, + + _fire: function(){ + var chain = this.chain; + var fired = this.fired; + var res = this.results[fired]; + var self = this; + var cb = null; + while(chain.length > 0 && this.paused == 0){ + // Array + var pair = chain.shift(); + var f = pair[fired]; + if(f == null){ + continue; + } + try { + res = f(res); + fired = ((res instanceof Error) ? 1 : 0); + if(res instanceof doh.Deferred){ + cb = function(res){ + self._continue(res); + }; + this._pause(); + } + }catch(err){ + fired = 1; + res = err; + } + } + this.fired = fired; + this.results[fired] = res; + if((cb)&&(this.paused)){ + res.addBoth(cb); + } + } +}); diff --git a/doh.js b/doh.js new file mode 100644 index 0000000..9f6604b --- /dev/null +++ b/doh.js @@ -0,0 +1,218 @@ +doh = { + + // This is a temporary structure which points to the current data. + _current:{ + group:null, + groupIndex:-1, + test:null, + testIndex:-1 + }, + // A helper property, which stores a reference to a test group by name. + _groupsByName:{}, + + // Statistical data. + _numTests:0, // The total number of tests. + _numTestsExecuted:0, // Number of tests already executed. + + // Stats about the test results. + _numErrors:0, + _numFailures:0, + + // + _isPaused:false, + _defaultTimeout:1000, + _testInFlight:false, + + // The groups must be an array, since an object does not necessarily maintain + // it's order, but tests should be executed in the order as added. + // This might become even more important when test dependencies will be added, + // which means only execute test2 if test1 succeeded. + _groups:[], + + pause:function(){ + this._isPaused = true; + }, + + register:function(groupName, tests){ + // summary: Register the given tests to the group with the given name. + // description: The tests are internally stored in "_groups", an array + // which contains all the tests per group. The new tests are added + // to the group with the given name, if it didnt exist yet it is created. + var group = null; + if (this._groupsByName[groupName]){ + group = this._groupsByName[groupName]; + } else { + this._groups.push({name:groupName, tests:[]}); + group = this._groupsByName[groupName] = this._groups[this._groups.length-1]; + } + for (var i=0, l=tests.length, t; i<l; i++){ + t = {}; + doh.mixin(t, tests[i]); + //t.test = doh.hitch(this, "_makeDeferred", [t.test]); + group.tests.push(t); + } + }, + + run:function(){ + this._isPaused = false; + if (this._testInFlight){ + return; + } + if (this._makeNextTestCurrent()){ + this._runTest(); + } + }, + + _getAssertWrapper:function(d){ + // summary: This returns an object which provides all the assert methods, and wraps a Deferred instance. + // description: Why that? The interface for doh tests should be the same + // for synchronous and asynchronous tests. The old version required + // you to "know" and "think" when writing asynch tests, and the + // assert methods had not been available directly when writing + // asynchronous tests, you had to use doh.callback/errback. + // This allows to ONLY use assert*() methods. See the selftests + // for examples. + var myT = new function(){ + this._assertClosure = function(method, args){ + // If the Deferred instance is already "done", means callback or errback + // had already been called dont do it again. + // This might be the case when e.g. the test timed out. + if (d.fired > -1){ + return; + } + try{ + var ret = doh[method].apply(doh, args); + d.callback(ret || true); + }catch(e){ + d.errback(e); + } + }; + for (var methodName in doh){ + if (methodName.indexOf("assert")===0){ + this[methodName] = (function(methodName){return function(){ + this._assertClosure(methodName, arguments); + }})(methodName); + } + } + }; + return myT; + }, + + _makeNextTestCurrent:function(){ + var c = this._current; + // Is there a test left in this group? + if (c.group && c.testIndex < c.group.tests.length-1){ + c.testIndex++; + } else { + // First test in the next group, if there is another group. + if (c.groupIndex < this._groups.length-1){ + c.groupIndex++; + c.group = this._groups[c.groupIndex]; + c.testIndex = 0; + } else { + return false; + } + } + c.test = c.group.tests[c.testIndex]; + return true; + }, + + _runNextTest:function(){ + // summary: Only called from internally after a test has finished. + if (this._isPaused){ + return; + } + if (this._makeNextTestCurrent()){ + this._runTest(); + } + }, + + _runTest:function(){ + // summary: This executes the current test. + // description: This method starts the "test" method of the test object + // and finishes by setting the internal state "_testInFlight" to true, + // which is resolved by the call to "_runNextTest()" which + // automatically happens after the (asynchronous) test has "landed". + var g = this._current.group, + t = this._current.test; + this._testStarted(g, t); + + // let doh reference "this.group.thinger..." which can be set by + // another test or group-level setUp function + t.group = g; + var deferred = new doh.Deferred(), + assertWrapperObject = this._getAssertWrapper(deferred); + if(t.setUp){ + t.setUp(assertWrapperObject); + } + if(!t.test){ + t.test = function(){deferred.errback(new Error("Test missing."));} + } + deferred.groupName = g.name; + deferred.test = t; + + deferred.addErrback(function(err){ + doh._handleFailure(g, t, err); + }); + + var retEnd = function(){ + t.endTime = new Date(); + if(t.tearDown){ + t.tearDown(assertWrapperObject); + } + doh._testEnd(g, t, deferred.results[0]); + } + + var timer = setTimeout(function(){ + deferred.errback(new Error("test timeout in " + t.name.toString())); + }, t.timeout || doh._defaultTimeout); + + deferred.addBoth(doh.hitch(this, function(arg){ + clearTimeout(timer); + retEnd(); + this._testInFlight = false; + setTimeout(doh.hitch(this, "_runNextTest"), 1); + })); + this._testInFlight = true; + + t.startTime = new Date(); + t.test(assertWrapperObject); + } +} + + + + +doh._testRegistered = function(group, fixture){ + // slot to be filled in +} + +doh._groupStarted = function(group){ + // slot to be filled in +} + +doh._groupFinished = function(group, success){ + // slot to be filled in +} + +doh._testStarted = function(group, fixture){ + // slot to be filled in +} + +doh._testFinished = function(group, fixture, success){ + // slot to be filled in +} + + + + + + +doh._testEnd = function(g, t, result){ + doh._currentTestCount++; + doh._testFinished(g, t, result); + if((!g.inFlight)&&(g.iterated)){ + doh._groupFinished(group.name, !g.failures); + } +} + diff --git a/index.html b/index.html new file mode 100644 index 0000000..e69de29 diff --git a/selftests.js b/selftests.js new file mode 100644 index 0000000..e5c3162 --- /dev/null +++ b/selftests.js @@ -0,0 +1,69 @@ + +doh.register("Synchronously written tests.", + [ + { + name:"fail: simple assertTrue", + test:function(t){ + t.assertTrue(false); + } + },{ + name:"success: simple assertTrue", + test:function(t){ + t.assertTrue(true); + } + },{ + name:"fail: timeout, assert() missing", + test:function(t){ + } + },{ + // This test will fail, because it has no implementation of the test method. + name:"fail: test() missing" + } + ] +); + +doh.register("Asynchronous tests.", + [ + { + // Inside of an asynch test case you can (and should) still use the assert() methods. + // No return necessary anymore!!! + name:"fail: simple asynch", + timeout:2000, + test:function(t){ + setTimeout(function(){ + t.assertTrue(false); + }, 1000); + } + }, + { + name:"success: simple asynch", + timeout:2000, + test:function(t){ + setTimeout(function(){ + t.assertTrue(true); + }, 1000); + } + }, + { + name:"fail: timeout", + timeout:100, // This timeout is shorter than the setTimeout below, this test should fail. + test:function(t){ + setTimeout(function(){ + t.assertTrue(true); + }, 1000); + } + }, + ] +); + +doh.register("Other features.", + [ + { + name:"success: pause after this test", + test:function(t){ + t.assertTrue(true); + doh.pause(); + } + }, + ] +); \ No newline at end of file diff --git a/ui.js b/ui.js new file mode 100644 index 0000000..d0eb4a6 --- /dev/null +++ b/ui.js @@ -0,0 +1,39 @@ +doh.ui = { + + started:function(){ + // summary: This is called when run() was called the first time. + console.log(doh._numTests + " tests registered, in " + doh._groups.length + " groups"); + console.log("--------"); + }, + + testRegistered:function(group, test){ + }, + + groupStarted:function(group){ + console.log("Starting group '" + group.name + "', " + group.tests.length + " tests"); + }, + + groupFinished:function(group){ + console.log(group.numTestsExecuted + " tests ran, " + + group.numFailures + " failures, " + + group.numErrors + " errors"); + console.log("--------"); + }, + + testStarted:function(group, test){ + }, + + testFailed:function(group, test, error){ + console.log(test.name + " FAILED, " + error); + }, + + testFinished:function(group, test, success){ + }, + + report:function(){ + console.log(doh._numTestsExecuted + " tests ran, " + + doh._numFailures + " failures, " + + doh._numErrors + " errors"); + console.log("========"); + } +} \ No newline at end of file diff --git a/util.js b/util.js new file mode 100644 index 0000000..417c34d --- /dev/null +++ b/util.js @@ -0,0 +1,77 @@ +// package system gunk. e +try{ + dojo.provide("doh.runner"); +}catch(e){ + if(!this["doh"]){ + doh = {}; + } +} + +// +// Utility Functions and Classes +// + +doh.selfTest = false; + +doh.global = this; + +doh.hitch = function(/*Object*/thisObject, /*Function|String*/method /*, ...*/){ + var args = []; + for(var x=2; x<arguments.length; x++){ + args.push(arguments[x]); + } + var fcn = ((typeof method == "string") ? thisObject[method] : method) || function(){}; + return function(){ + var ta = args.concat([]); // make a copy + for(var x=0; x<arguments.length; x++){ + ta.push(arguments[x]); + } + return fcn.apply(thisObject, ta); // Function + }; +} + +doh._mixin = function(/*Object*/ obj, /*Object*/ props){ + // summary: + // Adds all properties and methods of props to obj. This addition is + // "prototype extension safe", so that instances of objects will not + // pass along prototype defaults. + var tobj = {}; + for(var x in props){ + // the "tobj" condition avoid copying properties in "props" + // inherited from Object.prototype. For example, if obj has a custom + // toString() method, don't overwrite it with the toString() method + // that props inherited from Object.protoype + if(tobj[x] === undefined || tobj[x] != props[x]){ + obj[x] = props[x]; + } + } + // IE doesn't recognize custom toStrings in for..in + if( this["document"] + && document.all + && (typeof props["toString"] == "function") + && (props["toString"] != obj["toString"]) + && (props["toString"] != tobj["toString"]) + ){ + obj.toString = props.toString; + } + return obj; // Object +} + +doh.mixin = function(/*Object*/obj, /*Object...*/props){ + // summary: Adds all properties and methods of props to obj. + for(var i=1, l=arguments.length; i<l; i++){ + doh._mixin(obj, arguments[i]); + } + return obj; // Object +} + +doh.extend = function(/*Object*/ constructor, /*Object...*/ props){ + // summary: + // Adds all properties and methods of props to constructor's + // prototype, making them available to all instances created with + // constructor. + for(var i=1, l=arguments.length; i<l; i++){ + doh._mixin(constructor.prototype, arguments[i]); + } + return constructor; // Object +}
hookercookerman/calculated
5f2d4b9cd14655d58a5d35dad8c0791fbab80921
source data holder
diff --git a/lib/calculated/models/formula_input.rb b/lib/calculated/models/formula_input.rb index 8acc2f3..a5d8ac6 100644 --- a/lib/calculated/models/formula_input.rb +++ b/lib/calculated/models/formula_input.rb @@ -1,19 +1,20 @@ module Calculated module Models class FormulaInput < Hashie::Dash # properties property :id # [String] property :values # [Hash] property :name # [String] property :base_unit # [String] property :active_at # [Time] yes time property :main_source_id # [String] property :group_name # [String] property :input_units # [String] property :label_input_units # [String] property :model_state # [String] + property :source # holder of old data this is not used I repeat this is not used end end end \ No newline at end of file diff --git a/lib/calculated/version.rb b/lib/calculated/version.rb index 9ffb038..45313eb 100644 --- a/lib/calculated/version.rb +++ b/lib/calculated/version.rb @@ -1,3 +1,3 @@ module Calculated - VERSION = "0.1.0" + VERSION = "0.1.1" end \ No newline at end of file
hookercookerman/calculated
72f8c7b495059f439a553d098cbdd8762b8b9304
move it to markdown
diff --git a/README.md b/README.md index 7e42f6c..75a5087 100644 --- a/README.md +++ b/README.md @@ -1,290 +1,290 @@ #Calculated# Calculated allows you to interact with the [CarbonCalculated API](http://www.carboncalculated.com/platform) in a ruby way. "The Carbon Calculated platform is a freely accessible aggregation system containing up to the minute data on carbon emissions and emission calculation" * Idiomatic Ruby * Concrete classes and methods modelling CarbonCalculated data Please visit [The Blog](http://blog.carboncalculated.com) For Developer examples and information DOCS Are located [here](http://rdoc.info/projects/hookercookerman/calculated/blob/dd7ed3f73d987492486abb7091f6321e8b04443e) Super Simple Example Apps Using the API [http://miniapps.carboncalculated.com/](http://miniapps.carboncalculated.com/) ##Getting Started## Get An API KEY contact [email protected] You can install it as: sudo gem install calculated (dont use sudo if using RVM) ##Creating A Session## @session = Calculated::Session.create(:api_key => "your_api_key") ##Overwriting defaults## **These are the defaults** caching # => true (boolean) expires_in # => 60*60*24 (seconds) cache # => Moneta::Memory.new "(Moneta Supported Cache) http://github.com/wycats/moneta server # => "api.carboncalculated.com" (string) api_version #=> "v1" (string) logging # => true (boolean) **This is overriding the defaults** @session = Calculated::Session.create( :api_key => "your_api_key", :cache => Moneta::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], :bucket => 'carbon') :expires_in => 60*60*24*14 ) This has created a session with S3 Moneta cache that expires in 14 days ##Basic Usage## Via using the CarbonCalculated Browser http://browser.carboncalculated.com/ you can easily see what is available for you to interact with in terms of data and calculations; Now that you have a session you can call methods on the session to interact with carbon calculated api **Example** **Very simple materials Calculator** Lets first got to the calculator on the browser (click here to see what I mean http://browser.carboncalculated.com/calculators/4bab7e4ff78b122cdd000004/computations/4bab7e64f78b122cdd000005" @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] OR @answer = @session.answer_from_calculator("4bab7e4ff78b122cdd000004", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] This will return a Calculated::Models::Answer Object The reason that you can get an answer from either a calculator or a computation is the power of the validations; its cool trust me. ##Object Template Api## A Object Template is a template for the building of generic objects; these contain information about what all the object for the object template should contain; as well as getting relatable categories which can be used to filter to specific generic objects which you can then later be used in answer calls @object_templates = @session.object_templates # returns an Array of ObjectTemplate Objects @object_templates[0].name @object_templates[0].characteristics @object_template = @session.generic_objects_for_object_template("car") # returns an ObjectTemplate Object with paginate GenericObjects @object_template.generic_objects[0].identifier params can be given for pagination @session.object_templates(:page => 50, :per_page => 3) @session.generic_objects_for_object_template("car", :page => 50, :per_page => 3) # Getting object template with its relatable categories # this will return ObjectTemplate with Relatable Category Objects @object_template = @session.relatable_categories_for_object_template("car", "manufacture") @object_template.relatable_categories[0].name @object_template.relatable_categories[0].relatable_categories # yes relatable category know about other ones very cool when building "successive drop downs"[http://blog.carboncalculated.com/2010/06/16/creating-successive-drop-downs/] # @param [String] name # the object_template name ie "car", "airport", "material" # @param [String] filter # the string you want to filter # @object_template = @session.generic_objects_for_object_template_with_filter("airport", "london") @object_template.generic_objects[0].identifier ##Object Template Object## property :id # [String] property :template_name # [String] property :identifier # [String] property :characteristics # [Array<Calculated::Models::Characteristic>] property :formula_inputs # [Array<Calculated::Models::FormulaInput>] ##Generic Objects API## A Generic Object represents and object that is used in computations OR calculators; a computation will always need at least one object to talk about; The "formula_inputs" of an object are the values that are used in formulas and can be versioned to specific times for equations that change over time. This is a list of car for instance CLICK http://browser.carboncalculated.com/object_templates/car/generic_objects Finding and using generic objects is a major part of the platform apart from the actual calculations themselves # Finding generic objects @generic_objects = @session.generic_objects @generic_objects[0].identifier # Specific Generic Object @generic_object = @session.generic_object("4c370c11ae2b7b418e00232c") @generic_object.identifier # Getting just the "Formula Inputs" of a generic Object @formula_inputs = @session.formula_inputs_for_generic_object("4c370c11ae2b7b418e00232c") @formula_inputs[0].values ##Generic Object (Object)## - # properties - property :id # [String] - property :template_name # [String] - property :identifier # [String] - property :characteristics # [Array<Calculated::Models::Characteristic>] - property :formula_inputs # [Array<Calculated::Models::FormulaInput>] + # properties + property :id # [String] + property :template_name # [String] + property :identifier # [String] + property :characteristics # [Array<Calculated::Models::Characteristic>] + property :formula_inputs # [Array<Calculated::Models::FormulaInput>] ##Formula Input Object## - # properties - property :id # [String] - property :values # [Hash] - property :name # [String] - property :base_unit # [String] - property :active_at # [Time] yes time - property :main_source_id # [String] - property :group_name # [String] - property :input_units # [String] - property :label_input_units # [String] - property :model_state # [String] + # properties + property :id # [String] + property :values # [Hash] + property :name # [String] + property :base_unit # [String] + property :active_at # [Time] yes time + property :main_source_id # [String] + property :group_name # [String] + property :input_units # [String] + property :label_input_units # [String] + property :model_state # [String] ##Relatable Category API## Relatable Categories are created when an generic object has been created; And not before hand; Hence in theory a relatable category is only there when objects are there and not before; Which means that you should never have a problem of a category existing just for the fun of it; A relatable category will know all the objects that have its name and related_attribute; In a nut shell you can use relatable category to filter and find related objects easily and effectively; Also a relatable category will know of other relatable categories of the created object; so this allows for super easy drop downs to create easy filter; the blog should help explain this further or just send me an email; - # Getting related objects from an ARRAY OF Relatable Category IDS USED in intersecting the related objects - # therefore its a really cool way to get filtered results - # - # @param object_template_name ie "car", "material" - # @param relatable_category_ids # Array # - result = @session.related_objects_from_relatable_categories("material", ["4bf42d8a46a95925b500199a"]) - result["4bf42d8b46a95925b5001a0c"] # Partial Board + # Getting related objects from an ARRAY OF Relatable Category IDS USED in intersecting the related objects + # therefore its a really cool way to get filtered results + # + # @param object_template_name ie "car", "material" + # @param relatable_category_ids # Array # + result = @session.related_objects_from_relatable_categories("material", ["4bf42d8a46a95925b500199a"]) + result["4bf42d8b46a95925b5001a0c"] # Partial Board - # Getting Related Categories from a related category - # - # @param Relatable Category ID - # @param related_attribute - result = @session.related_categories_from_relatable_category("4bf42d8a46a95925b500199a", "material_type") - results["4bf42d8b46a95925b50019c7"] # hardboard + # Getting Related Categories from a related category + # + # @param Relatable Category ID + # @param related_attribute + result = @session.related_categories_from_relatable_category("4bf42d8a46a95925b500199a", "material_type") + results["4bf42d8b46a95925b50019c7"] # hardboard ##Relatable Category Object## - # properties - property :id # [String] - property :name # [String] - property :related_attribute # [String] - property :related_object_name # [String] - # @example - # "emission_source" => { - # { - # "4c349f6068fe5434960178c2" => "flaring and venting", - # "4c349f6068fe54349601791f" => "fugitives", - # } - # } - property :related_categories # [Hash{name => <Hash{:id => identifier}}] + # properties + property :id # [String] + property :name # [String] + property :related_attribute # [String] + property :related_object_name # [String] + # @example + # "emission_source" => { + # { + # "4c349f6068fe5434960178c2" => "flaring and venting", + # "4c349f6068fe54349601791f" => "fugitives", + # } + # } + property :related_categories # [Hash{name => <Hash{:id => identifier}}] ##Answer API## This is the crux of the api; this is where co2, co2e etc results can be found; The best and easiest way to found what information you need to get a valid answer is using the browser["http://browser.carboncalculated.com"] Once you have found what parameters you need to send you can then do exactly that; A Answer Object will give you vaste information on what it used to get the answer; You will be told the all the objects that were used in the calculation all the used_formula_inputs and the sources that where used to gain the information to make the calculation even possible. - @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) - @answer.calculations["co2"]["value"] + @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) + @answer.calculations["co2"]["value"] *Errors If you don send the correct parameters in an answer you will be told where you are going wrong - @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "formula_input_name"=>"emissions_by_kg"}) - @answer.valid? # false + @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "formula_input_name"=>"emissions_by_kg"}) + @answer.valid? # false - @answer.errors + @answer.errors - "amount_of_material" =>["can't be blank", "is not a number"] + "amount_of_material" =>["can't be blank", "is not a number"] ##Answer Object## - # answer.calculations["co2"]["value"] == 10 - # answer.calculations["co2"]["units"] == "kg" - # - property :calculations # [Hash] - property :object_references # [Hash] - property :used_global_computations # [Hash] - property :calculator_id # [String] - property :computation_id # [String] - property :answer_set_id # [String] - property :source # [Calculated::Models::Source] - property :errors # [Hash] + # answer.calculations["co2"]["value"] == 10 + # answer.calculations["co2"]["units"] == "kg" + # + property :calculations # [Hash] + property :object_references # [Hash] + property :used_global_computations # [Hash] + property :calculator_id # [String] + property :computation_id # [String] + property :answer_set_id # [String] + property :source # [Calculated::Models::Source] + property :errors # [Hash] ##Source Object## - # properties - property :id # [String] - property :description # [String] - property :main_source_ids # [Array<String>] - property :external_url # [String] - property :wave_id # [String] + # properties + property :id # [String] + property :description # [String] + property :main_source_ids # [Array<String>] + property :external_url # [String] + property :wave_id # [String] ##Bugs and Feedback## If you discover any bugs or want to drop a line [email protected] Copyright (c) 2010 Richard Hooker http://blog.carboncalculated.com See the attached MIT License.
hookercookerman/calculated
5966ce3b13d156db7510f4e6be89f23434ee7de6
move it to markdown
diff --git a/README.md b/README.md index 6ff70d2..7e42f6c 100644 --- a/README.md +++ b/README.md @@ -1,291 +1,290 @@ #Calculated# Calculated allows you to interact with the [CarbonCalculated API](http://www.carboncalculated.com/platform) in a ruby way. "The Carbon Calculated platform is a freely accessible aggregation system containing up to the minute data on carbon emissions and emission calculation" * Idiomatic Ruby * Concrete classes and methods modelling CarbonCalculated data Please visit [The Blog](http://blog.carboncalculated.com) For Developer examples and information DOCS Are located [here](http://rdoc.info/projects/hookercookerman/calculated/blob/dd7ed3f73d987492486abb7091f6321e8b04443e) Super Simple Example Apps Using the API [http://miniapps.carboncalculated.com/](http://miniapps.carboncalculated.com/) ##Getting Started## Get An API KEY contact [email protected] You can install it as: sudo gem install calculated (dont use sudo if using RVM) ##Creating A Session## @session = Calculated::Session.create(:api_key => "your_api_key") ##Overwriting defaults## **These are the defaults** caching # => true (boolean) expires_in # => 60*60*24 (seconds) cache # => Moneta::Memory.new "(Moneta Supported Cache) http://github.com/wycats/moneta server # => "api.carboncalculated.com" (string) api_version #=> "v1" (string) logging # => true (boolean) **This is overriding the defaults** @session = Calculated::Session.create( :api_key => "your_api_key", :cache => Moneta::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], :bucket => 'carbon') :expires_in => 60*60*24*14 ) This has created a session with S3 Moneta cache that expires in 14 days ##Basic Usage## Via using the CarbonCalculated Browser http://browser.carboncalculated.com/ you can easily see what is available for you to interact with in terms of data and calculations; Now that you have a session you can call methods on the session to interact with carbon calculated api **Example** **Very simple materials Calculator** Lets first got to the calculator on the browser (click here to see what I mean http://browser.carboncalculated.com/calculators/4bab7e4ff78b122cdd000004/computations/4bab7e64f78b122cdd000005" @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] OR @answer = @session.answer_from_calculator("4bab7e4ff78b122cdd000004", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] This will return a Calculated::Models::Answer Object The reason that you can get an answer from either a calculator or a computation is the power of the validations; its cool trust me. ##Object Template Api## A Object Template is a template for the building of generic objects; these contain information about what all the object for the object template should contain; as well as getting relatable categories which can be used to filter to specific generic objects which you can then later be used in answer calls @object_templates = @session.object_templates # returns an Array of ObjectTemplate Objects @object_templates[0].name @object_templates[0].characteristics @object_template = @session.generic_objects_for_object_template("car") # returns an ObjectTemplate Object with paginate GenericObjects @object_template.generic_objects[0].identifier params can be given for pagination @session.object_templates(:page => 50, :per_page => 3) @session.generic_objects_for_object_template("car", :page => 50, :per_page => 3) # Getting object template with its relatable categories # this will return ObjectTemplate with Relatable Category Objects @object_template = @session.relatable_categories_for_object_template("car", "manufacture") @object_template.relatable_categories[0].name @object_template.relatable_categories[0].relatable_categories # yes relatable category know about other ones very cool when building "successive drop downs"[http://blog.carboncalculated.com/2010/06/16/creating-successive-drop-downs/] # @param [String] name # the object_template name ie "car", "airport", "material" # @param [String] filter # the string you want to filter # @object_template = @session.generic_objects_for_object_template_with_filter("airport", "london") @object_template.generic_objects[0].identifier ##Object Template Object## property :id # [String] property :template_name # [String] property :identifier # [String] property :characteristics # [Array<Calculated::Models::Characteristic>] property :formula_inputs # [Array<Calculated::Models::FormulaInput>] ##Generic Objects API## A Generic Object represents and object that is used in computations OR calculators; a computation will always need at least one object to talk about; The "formula_inputs" of an object are the values that are used in formulas and can be versioned to specific times for equations that change over time. This is a list of car for instance CLICK http://browser.carboncalculated.com/object_templates/car/generic_objects Finding and using generic objects is a major part of the platform apart from the actual calculations themselves - # Finding generic objects - @generic_objects = @session.generic_objects - @generic_objects[0].identifier + # Finding generic objects + @generic_objects = @session.generic_objects + @generic_objects[0].identifier - - - # Specific Generic Object - @generic_object = @session.generic_object("4c370c11ae2b7b418e00232c") - @generic_object.identifier + + # Specific Generic Object + @generic_object = @session.generic_object("4c370c11ae2b7b418e00232c") + @generic_object.identifier - # Getting just the "Formula Inputs" of a generic Object - @formula_inputs = @session.formula_inputs_for_generic_object("4c370c11ae2b7b418e00232c") - @formula_inputs[0].values + # Getting just the "Formula Inputs" of a generic Object + @formula_inputs = @session.formula_inputs_for_generic_object("4c370c11ae2b7b418e00232c") + @formula_inputs[0].values ##Generic Object (Object)## # properties property :id # [String] property :template_name # [String] property :identifier # [String] property :characteristics # [Array<Calculated::Models::Characteristic>] property :formula_inputs # [Array<Calculated::Models::FormulaInput>] ##Formula Input Object## # properties property :id # [String] property :values # [Hash] property :name # [String] property :base_unit # [String] property :active_at # [Time] yes time property :main_source_id # [String] property :group_name # [String] property :input_units # [String] property :label_input_units # [String] property :model_state # [String] ##Relatable Category API## Relatable Categories are created when an generic object has been created; And not before hand; Hence in theory a relatable category is only there when objects are there and not before; Which means that you should never have a problem of a category existing just for the fun of it; A relatable category will know all the objects that have its name and related_attribute; In a nut shell you can use relatable category to filter and find related objects easily and effectively; Also a relatable category will know of other relatable categories of the created object; so this allows for super easy drop downs to create easy filter; the blog should help explain this further or just send me an email; # Getting related objects from an ARRAY OF Relatable Category IDS USED in intersecting the related objects # therefore its a really cool way to get filtered results # # @param object_template_name ie "car", "material" # @param relatable_category_ids # Array # result = @session.related_objects_from_relatable_categories("material", ["4bf42d8a46a95925b500199a"]) result["4bf42d8b46a95925b5001a0c"] # Partial Board # Getting Related Categories from a related category # # @param Relatable Category ID # @param related_attribute result = @session.related_categories_from_relatable_category("4bf42d8a46a95925b500199a", "material_type") results["4bf42d8b46a95925b50019c7"] # hardboard ##Relatable Category Object## # properties property :id # [String] property :name # [String] property :related_attribute # [String] property :related_object_name # [String] # @example # "emission_source" => { # { # "4c349f6068fe5434960178c2" => "flaring and venting", # "4c349f6068fe54349601791f" => "fugitives", # } # } property :related_categories # [Hash{name => <Hash{:id => identifier}}] ##Answer API## This is the crux of the api; this is where co2, co2e etc results can be found; The best and easiest way to found what information you need to get a valid answer is using the browser["http://browser.carboncalculated.com"] Once you have found what parameters you need to send you can then do exactly that; A Answer Object will give you vaste information on what it used to get the answer; You will be told the all the objects that were used in the calculation all the used_formula_inputs and the sources that where used to gain the information to make the calculation even possible. @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] *Errors If you don send the correct parameters in an answer you will be told where you are going wrong @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "formula_input_name"=>"emissions_by_kg"}) @answer.valid? # false @answer.errors "amount_of_material" =>["can't be blank", "is not a number"] ##Answer Object## # answer.calculations["co2"]["value"] == 10 # answer.calculations["co2"]["units"] == "kg" # property :calculations # [Hash] property :object_references # [Hash] property :used_global_computations # [Hash] property :calculator_id # [String] property :computation_id # [String] property :answer_set_id # [String] property :source # [Calculated::Models::Source] property :errors # [Hash] ##Source Object## # properties property :id # [String] property :description # [String] property :main_source_ids # [Array<String>] property :external_url # [String] property :wave_id # [String] ##Bugs and Feedback## If you discover any bugs or want to drop a line [email protected] Copyright (c) 2010 Richard Hooker http://blog.carboncalculated.com See the attached MIT License.
hookercookerman/calculated
46525ae09508160f376f63d032310127dd4475a6
move it to markdown
diff --git a/README.md b/README.md new file mode 100644 index 0000000..6ff70d2 --- /dev/null +++ b/README.md @@ -0,0 +1,291 @@ +#Calculated# + +Calculated allows you to interact with the [CarbonCalculated API](http://www.carboncalculated.com/platform) in +a ruby way. + +"The Carbon Calculated platform is a freely accessible aggregation system containing up to the minute data on carbon emissions and emission calculation" + +* Idiomatic Ruby +* Concrete classes and methods modelling CarbonCalculated data + +Please visit [The Blog](http://blog.carboncalculated.com) For Developer examples and information + +DOCS Are located [here](http://rdoc.info/projects/hookercookerman/calculated/blob/dd7ed3f73d987492486abb7091f6321e8b04443e) + +Super Simple Example Apps Using the API + +[http://miniapps.carboncalculated.com/](http://miniapps.carboncalculated.com/) + +##Getting Started## + +Get An API KEY + + contact [email protected] + +You can install it as: + + sudo gem install calculated (dont use sudo if using RVM) + +##Creating A Session## + + @session = Calculated::Session.create(:api_key => "your_api_key") + +##Overwriting defaults## + +**These are the defaults** + + caching # => true (boolean) + expires_in # => 60*60*24 (seconds) + cache # => Moneta::Memory.new "(Moneta Supported Cache) http://github.com/wycats/moneta + server # => "api.carboncalculated.com" (string) + api_version #=> "v1" (string) + logging # => true (boolean) + +**This is overriding the defaults** + + @session = Calculated::Session.create( + :api_key => "your_api_key", + :cache => Moneta::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], :bucket => 'carbon') + :expires_in => 60*60*24*14 + ) + + This has created a session with S3 Moneta cache that expires in 14 days + +##Basic Usage## + +Via using the CarbonCalculated Browser http://browser.carboncalculated.com/ you can easily see what is available for you to interact with in terms of +data and calculations; + +Now that you have a session you can call methods on the session to interact with carbon calculated api + +**Example** + +**Very simple materials Calculator** + +Lets first got to the calculator on the browser (click here to see what I mean http://browser.carboncalculated.com/calculators/4bab7e4ff78b122cdd000004/computations/4bab7e64f78b122cdd000005" + + @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) + @answer.calculations["co2"]["value"] + + + + OR + + + @answer = @session.answer_from_calculator("4bab7e4ff78b122cdd000004", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) + @answer.calculations["co2"]["value"] + + This will return a Calculated::Models::Answer Object + + + The reason that you can get an answer from either a calculator or a computation is the power of the validations; its cool + trust me. + +##Object Template Api## + +A Object Template is a template for the building of generic objects; these contain information about what +all the object for the object template should contain; as well as getting relatable categories which can be +used to filter to specific generic objects which you can then later be used in answer calls + + @object_templates = @session.object_templates # returns an Array of ObjectTemplate Objects + @object_templates[0].name + @object_templates[0].characteristics + + + + + @object_template = @session.generic_objects_for_object_template("car") # returns an ObjectTemplate Object with paginate GenericObjects + @object_template.generic_objects[0].identifier + + + + + + params can be given for pagination + @session.object_templates(:page => 50, :per_page => 3) + @session.generic_objects_for_object_template("car", :page => 50, :per_page => 3) + + + + + + # Getting object template with its relatable categories + # this will return ObjectTemplate with Relatable Category Objects + @object_template = @session.relatable_categories_for_object_template("car", "manufacture") + @object_template.relatable_categories[0].name + @object_template.relatable_categories[0].relatable_categories + + # yes relatable category know about other ones very cool when building "successive drop downs"[http://blog.carboncalculated.com/2010/06/16/creating-successive-drop-downs/] + + + + + + # @param [String] name # the object_template name ie "car", "airport", "material" + # @param [String] filter # the string you want to filter + # + @object_template = @session.generic_objects_for_object_template_with_filter("airport", "london") + @object_template.generic_objects[0].identifier + +##Object Template Object## + + property :id # [String] + property :template_name # [String] + property :identifier # [String] + property :characteristics # [Array<Calculated::Models::Characteristic>] + property :formula_inputs # [Array<Calculated::Models::FormulaInput>] + +##Generic Objects API## + +A Generic Object represents and object that is used in computations OR calculators; a computation will always +need at least one object to talk about; The "formula_inputs" of an object are the values that are used +in formulas and can be versioned to specific times for equations that change over time. + +This is a list of car for instance CLICK http://browser.carboncalculated.com/object_templates/car/generic_objects + +Finding and using generic objects is a major part of the platform apart from the actual calculations themselves + + # Finding generic objects + @generic_objects = @session.generic_objects + @generic_objects[0].identifier + + + + # Specific Generic Object + @generic_object = @session.generic_object("4c370c11ae2b7b418e00232c") + @generic_object.identifier + + + + # Getting just the "Formula Inputs" of a generic Object + @formula_inputs = @session.formula_inputs_for_generic_object("4c370c11ae2b7b418e00232c") + @formula_inputs[0].values + +##Generic Object (Object)## + + # properties + property :id # [String] + property :template_name # [String] + property :identifier # [String] + property :characteristics # [Array<Calculated::Models::Characteristic>] + property :formula_inputs # [Array<Calculated::Models::FormulaInput>] + +##Formula Input Object## + + # properties + property :id # [String] + property :values # [Hash] + property :name # [String] + property :base_unit # [String] + property :active_at # [Time] yes time + property :main_source_id # [String] + property :group_name # [String] + property :input_units # [String] + property :label_input_units # [String] + property :model_state # [String] + +##Relatable Category API## + +Relatable Categories are created when an generic object has been created; And not before hand; Hence +in theory a relatable category is only there when objects are there and not before; Which means +that you should never have a problem of a category existing just for the fun of it; + +A relatable category will know all the objects that have its name and related_attribute; In a nut shell you can use relatable +category to filter and find related objects easily and effectively; + +Also a relatable category will know of other relatable categories of the created object; so this allows for +super easy drop downs to create easy filter; the blog should help explain this further or just send me an email; + + + + # Getting related objects from an ARRAY OF Relatable Category IDS USED in intersecting the related objects + # therefore its a really cool way to get filtered results + # + # @param object_template_name ie "car", "material" + # @param relatable_category_ids # Array # + result = @session.related_objects_from_relatable_categories("material", ["4bf42d8a46a95925b500199a"]) + result["4bf42d8b46a95925b5001a0c"] # Partial Board + + + + + + # Getting Related Categories from a related category + # + # @param Relatable Category ID + # @param related_attribute + result = @session.related_categories_from_relatable_category("4bf42d8a46a95925b500199a", "material_type") + results["4bf42d8b46a95925b50019c7"] # hardboard + + +##Relatable Category Object## + + # properties + property :id # [String] + property :name # [String] + property :related_attribute # [String] + property :related_object_name # [String] + # @example + # "emission_source" => { + # { + # "4c349f6068fe5434960178c2" => "flaring and venting", + # "4c349f6068fe54349601791f" => "fugitives", + # } + # } + property :related_categories # [Hash{name => <Hash{:id => identifier}}] + + +##Answer API## + +This is the crux of the api; this is where co2, co2e etc results can be found; + +The best and easiest way to found what information you need to get a valid answer is using the browser["http://browser.carboncalculated.com"] +Once you have found what parameters you need to send you can then do exactly that; + +A Answer Object will give you vaste information on what it used to get the answer; You will be told the all the objects that were used in the calculation +all the used_formula_inputs and the sources that where used to gain the information to make the calculation even possible. + + + @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) + @answer.calculations["co2"]["value"] + +*Errors + +If you don send the correct parameters in an answer you will be told where you are going wrong + + @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "formula_input_name"=>"emissions_by_kg"}) + @answer.valid? # false + + @answer.errors + + "amount_of_material" =>["can't be blank", "is not a number"] + +##Answer Object## + + # answer.calculations["co2"]["value"] == 10 + # answer.calculations["co2"]["units"] == "kg" + # + property :calculations # [Hash] + property :object_references # [Hash] + property :used_global_computations # [Hash] + property :calculator_id # [String] + property :computation_id # [String] + property :answer_set_id # [String] + property :source # [Calculated::Models::Source] + property :errors # [Hash] + +##Source Object## + + # properties + property :id # [String] + property :description # [String] + property :main_source_ids # [Array<String>] + property :external_url # [String] + property :wave_id # [String] + +##Bugs and Feedback## + +If you discover any bugs or want to drop a line [email protected] + +Copyright (c) 2010 Richard Hooker http://blog.carboncalculated.com +See the attached MIT License.
hookercookerman/calculated
2bd99348f9fcb5055159790ab7ceb96ed51a94f4
Another doc update
diff --git a/README.rdoc b/README.rdoc index 30f2686..1af7390 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,248 +1,260 @@ = Calculated Calculated allows you to interact with the "CarbonCalculated API"[http://www.carboncalculated.com/platform] in a ruby way. "The Carbon Calculated platform is a freely accessible aggregation system containing up to the minute data on carbon emissions and emission calculation" * Idiomatic Ruby * Concrete classes and methods modelling CarbonCalculated data Please visit ["http://blog.carboncalculated.com"] For Developer examples and information == Getting Started Get An API KEY contact [email protected] You can install it as: sudo gem install calculated (dont use sudo if using RVM) == Creating A Session @session = Calculated::Session.create(:api_key => "your_api_key") == Overwriting defaults These are the defaults caching # => true (boolean) expires_in # => 60*60*24 (seconds) cache # => Moneta::Memory.new "(Moneta Supported Cache) http://github.com/wycats/moneta server # => "api.carboncalculated.com" (string) api_version #=> "v1" (string) logging # => true (boolean) This is overriding the defaults @session = Calculated::Session.create( :api_key => "your_api_key", :cache => Moneta::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], :bucket => 'carbon') :expires_in => 60*60*24*14 ) This has created a session with S3 Moneta cache that expires in 14 days == Basic Usage Via using the "CarbonCalculated Browser"["http://browswer.carboncalculated.com"] you can easily see what is available for you to interact with in terms of data and calculations; Now that you have a session you can call methods on the session to interact with carbon calculated api *Example Very simple materials Calculator Lets first got to the calculator on the browser (click here to see what I mean)["http://browser.carboncalculated.com/calculators/4bab7e4ff78b122cdd000004/computations/4bab7e64f78b122cdd000005"] @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] OR @answer = @session.answer_from_calculator("4bab7e4ff78b122cdd000004", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] This will return a Calculated::Models::Answer Object The reason that you can get an answer from either a calculator or a computation is the power of the validations; its cool trust me. == Object Template Api A Object Template is a template for the building of generic objects; these contain information about what all the object for the object template should contain; as well as getting relatable categories which can be used to filter to specific generic objects which you can then later be used in answer calls @object_templates = @session.object_templates # returns an Array of ObjectTemplate Objects @object_templates[0].name @object_templates[0].characteristics @object_template = @session.generic_objects_for_object_template("car") # returns an ObjectTemplate Object with paginate GenericObjects @object_template.generic_objects[0].identifier params can be given for pagination @session.object_templates(:page => 50, :per_page => 3) @session.generic_objects_for_object_template("car", :page => 50, :per_page => 3) # Getting object template with its relatable categories # this will return ObjectTemplate with Relatable Category Objects @object_template = @session.relatable_categories_for_object_template("car", "manufacture") @object_template.relatable_categories[0].name @object_template.relatable_categories[0].relatable_categories # yes relatable category know about other ones very cool when building "successive drop downs"[http://blog.carboncalculated.com/2010/06/16/creating-successive-drop-downs/] # @param [String] name # the object_template name ie "car", "airport", "material" # @param [String] filter # the string you want to filter # @object_template = @session.generic_objects_for_object_template_with_filter("airport", "london") @object_template.generic_objects[0].identifier == Object Template Object property :id # [String] property :template_name # [String] property :identifier # [String] property :characteristics # [Array<Calculated::Models::Characteristic>] property :formula_inputs # [Array<Calculated::Models::FormulaInput>] == Generic Objects API A Generic Object represents and object that is used in computations OR calculators; a computation will always need at least one object to talk about; The "formula_inputs" of an object are the values that are used in formulas and can be versioned to specific times for equations that change over time. This is a list of car for instance "CLICK ME"[http://browser.carboncalculated.com/object_templates/car/generic_objects] Finding and using generic objects is a major part of the platform apart from the actual calculations themselves # Finding general generic objects @generic_objects = @session.generic_objects @generic_objects[0].identifier # Getting Specific Generic Object @generic_object = @session.generic_object("4c370c11ae2b7b418e00232c") @generic_object.identifier # Getting just the "Formula Inputs" of a generic Object @formula_inputs = @session.formula_inputs_for_generic_object("4c370c11ae2b7b418e00232c") @formula_inputs[0].values == Generic Object (Object) # properties property :id # [String] property :template_name # [String] property :identifier # [String] property :characteristics # [Array<Calculated::Models::Characteristic>] property :formula_inputs # [Array<Calculated::Models::FormulaInput>] == Formula Input Object # properties property :id # [String] property :values # [Hash] property :name # [String] property :base_unit # [String] property :active_at # [Time] yes time property :main_source_id # [String] property :group_name # [String] property :input_units # [String] property :label_input_units # [String] property :model_state # [String] == Relatable Category API Relatable Categories are created when an generic object has been created; And not before hand; Hence in theory a relatable category is only there when objects are there and not before; Which means that you should never have a problem of a category existing just for the fun of it; A relatable category will know all the objects that have its name and related_attribute; In a nut shell you can use relatable category to filter and find related objects easily and effectively; Also a relatable category will know of other relatable categories of the created object; so this allows for super easy drop downs to create easy filter; the blog should help explain this further or just send me an email; # Getting related objects from an ARRAY OF Relatable Category IDS USED in intersecting the related objects # therefore its a really cool way to get filtered results # # @param object_template_name ie "car", "material" # @param relatable_category_ids # Array # result = @session.related_objects_from_relatable_categories("material", ["4bf42d8a46a95925b500199a"]) result["4bf42d8b46a95925b5001a0c"] # Partial Board # Getting Related Categories from a related category # # @param Relatable Category ID # @param related_attribute result = @session.related_categories_from_relatable_category("4bf42d8a46a95925b500199a", "material_type") results["4bf42d8b46a95925b50019c7"] # hardboard == Relatable Category Object # properties property :id # [String] property :name # [String] property :related_attribute # [String] property :related_object_name # [String] # @example # "emission_source" => { # { # "4c349f6068fe5434960178c2" => "flaring and venting", # "4c349f6068fe54349601791f" => "fugitives", # } # } property :related_categories # [Hash{name => <Hash{:id => identifier}}] == Answer API This is the crux of the api; this is where co2, co2e etc results can be found; The best and easiest way to found what information you need to get a valid answer is using the browser["http://browser.carboncalculated.com"] -Once you have found what parameters you need to send you can then do exactly that +Once you have found what parameters you need to send you can then do exactly that; + +A Answer Object will give you vaste information on what it used to get the answer; You will be told the all the objects that were used in the calculation +all the used_formula_inputs and the sources that where used to gain the information to make the calculation even possible. @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] *Errors If you don send the correct parameters in an answer you will be told where you are going wrong @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "formula_input_name"=>"emissions_by_kg"}) @answer.valid? # false @answer.errors "amount_of_material" =>["can't be blank", "is not a number"] == Answer Object # answer.calculations["co2"]["value"] == 10 # answer.calculations["co2"]["units"] == "kg" # property :calculations # [Hash] property :object_references # [Hash] property :used_global_computations # [Hash] property :calculator_id # [String] property :computation_id # [String] property :answer_set_id # [String] property :source # [Calculated::Models::Source] property :errors # [Hash] + +== Source Object + # properties + property :id # [String] + property :description # [String] + property :main_source_ids # [Array<String>] + property :external_url # [String] + property :wave_id # [String] + == Bugs and Feedback If you discover any bugs or want to drop a line Copyright (c) 2010 Richard Hooker http://blog.carboncalculated.com See the attached MIT License.
hookercookerman/calculated
dcaf34b0fc08ae3e89fcbd6534140486c6551261
Updating docs still alot need to be done
diff --git a/README.rdoc b/README.rdoc index 709f336..30f2686 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,117 +1,248 @@ -== Calculated += Calculated Calculated allows you to interact with the "CarbonCalculated API"[http://www.carboncalculated.com/platform] in a ruby way. "The Carbon Calculated platform is a freely accessible aggregation system containing up to the minute data on carbon emissions and emission calculation" * Idiomatic Ruby * Concrete classes and methods modelling CarbonCalculated data +Please visit ["http://blog.carboncalculated.com"] For Developer examples and information + == Getting Started Get An API KEY contact [email protected] You can install it as: sudo gem install calculated (dont use sudo if using RVM) == Creating A Session @session = Calculated::Session.create(:api_key => "your_api_key") == Overwriting defaults These are the defaults caching # => true (boolean) expires_in # => 60*60*24 (seconds) - cache # => Moneta::Memory.new "(Moneta Supported Cache)"[http://github.com/wycats/moneta] + cache # => Moneta::Memory.new "(Moneta Supported Cache) http://github.com/wycats/moneta server # => "api.carboncalculated.com" (string) api_version #=> "v1" (string) logging # => true (boolean) This is overriding the defaults @session = Calculated::Session.create( :api_key => "your_api_key", :cache => Moneta::S3.new(:access_key_id => ENV['AWS_ACCESS_KEY_ID'], :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'], :bucket => 'carbon') :expires_in => 60*60*24*14 ) This has created a session with S3 Moneta cache that expires in 14 days == Basic Usage Via using the "CarbonCalculated Browser"["http://browswer.carboncalculated.com"] you can easily see what is available for you to interact with in terms of data and calculations; Now that you have a session you can call methods on the session to interact with carbon calculated api *Example Very simple materials Calculator -Lets first got to the calculator on the browser "click here to see what I mean"["http://browser.carboncalculated.com/calculators/4bab7e4ff78b122cdd000004/computations/4bab7e64f78b122cdd000005"] +Lets first got to the calculator on the browser (click here to see what I mean)["http://browser.carboncalculated.com/calculators/4bab7e4ff78b122cdd000004/computations/4bab7e64f78b122cdd000005"] @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] OR @answer = @session.answer_from_calculator("4bab7e4ff78b122cdd000004", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) @answer.calculations["co2"]["value"] This will return a Calculated::Models::Answer Object The reason that you can get an answer from either a calculator or a computation is the power of the validations; its cool trust me. == Object Template Api A Object Template is a template for the building of generic objects; these contain information about what all the object for the object template should contain; as well as getting relatable categories which can be used to filter to specific generic objects which you can then later be used in answer calls - @session.object_templates # returns an Array of ObjectTemplate Objects + @object_templates = @session.object_templates # returns an Array of ObjectTemplate Objects + @object_templates[0].name + @object_templates[0].characteristics - @session.generic_objects_for_object_template("car") # returns an ObjectTemplate Object with paginate GenericObjects + @object_template = @session.generic_objects_for_object_template("car") # returns an ObjectTemplate Object with paginate GenericObjects + @object_template.generic_objects[0].identifier params can be given for pagination @session.object_templates(:page => 50, :per_page => 3) @session.generic_objects_for_object_template("car", :page => 50, :per_page => 3) # Getting object template with its relatable categories # this will return ObjectTemplate with Relatable Category Objects @object_template = @session.relatable_categories_for_object_template("car", "manufacture") @object_template.relatable_categories[0].name @object_template.relatable_categories[0].relatable_categories # yes relatable category know about other ones very cool when building "successive drop downs"[http://blog.carboncalculated.com/2010/06/16/creating-successive-drop-downs/] + + + # @param [String] name # the object_template name ie "car", "airport", "material" + # @param [String] filter # the string you want to filter + # + @object_template = @session.generic_objects_for_object_template_with_filter("airport", "london") + @object_template.generic_objects[0].identifier + +== Object Template Object + + property :id # [String] + property :template_name # [String] + property :identifier # [String] + property :characteristics # [Array<Calculated::Models::Characteristic>] + property :formula_inputs # [Array<Calculated::Models::FormulaInput>] + +== Generic Objects API + +A Generic Object represents and object that is used in computations OR calculators; a computation will always +need at least one object to talk about; The "formula_inputs" of an object are the values that are used +in formulas and can be versioned to specific times for equations that change over time. + +This is a list of car for instance "CLICK ME"[http://browser.carboncalculated.com/object_templates/car/generic_objects] + +Finding and using generic objects is a major part of the platform apart from the actual calculations themselves + + # Finding general generic objects + @generic_objects = @session.generic_objects + @generic_objects[0].identifier + + # Getting Specific Generic Object + @generic_object = @session.generic_object("4c370c11ae2b7b418e00232c") + @generic_object.identifier + + # Getting just the "Formula Inputs" of a generic Object + @formula_inputs = @session.formula_inputs_for_generic_object("4c370c11ae2b7b418e00232c") + @formula_inputs[0].values + + +== Generic Object (Object) + + # properties + property :id # [String] + property :template_name # [String] + property :identifier # [String] + property :characteristics # [Array<Calculated::Models::Characteristic>] + property :formula_inputs # [Array<Calculated::Models::FormulaInput>] +== Formula Input Object + + # properties + property :id # [String] + property :values # [Hash] + property :name # [String] + property :base_unit # [String] + property :active_at # [Time] yes time + property :main_source_id # [String] + property :group_name # [String] + property :input_units # [String] + property :label_input_units # [String] + property :model_state # [String] + +== Relatable Category API + +Relatable Categories are created when an generic object has been created; And not before hand; Hence +in theory a relatable category is only there when objects are there and not before; Which means +that you should never have a problem of a category existing just for the fun of it; + +A relatable category will know all the objects that have its name and related_attribute; In a nut shell you can use relatable +category to filter and find related objects easily and effectively; + +Also a relatable category will know of other relatable categories of the created object; so this allows for +super easy drop downs to create easy filter; the blog should help explain this further or just send me an email; + + # Getting related objects from an ARRAY OF Relatable Category IDS USED in intersecting the related objects + # therefore its a really cool way to get filtered results + # + # @param object_template_name ie "car", "material" + # @param relatable_category_ids # Array # + result = @session.related_objects_from_relatable_categories("material", ["4bf42d8a46a95925b500199a"]) + result["4bf42d8b46a95925b5001a0c"] # Partial Board + + # Getting Related Categories from a related category + # + # @param Relatable Category ID + # @param related_attribute + result = @session.related_categories_from_relatable_category("4bf42d8a46a95925b500199a", "material_type") + results["4bf42d8b46a95925b50019c7"] # hardboard + + +== Relatable Category Object + + # properties + property :id # [String] + property :name # [String] + property :related_attribute # [String] + property :related_object_name # [String] + # @example + # "emission_source" => { + # { + # "4c349f6068fe5434960178c2" => "flaring and venting", + # "4c349f6068fe54349601791f" => "fugitives", + # } + # } + property :related_categories # [Hash{name => <Hash{:id => identifier}}] + + +== Answer API + +This is the crux of the api; this is where co2, co2e etc results can be found; + +The best and easiest way to found what information you need to get a valid answer is using the browser["http://browser.carboncalculated.com"] +Once you have found what parameters you need to send you can then do exactly that + + + @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "amount_of_material"=>"10", "formula_input_name"=>"emissions_by_kg"}) + @answer.calculations["co2"]["value"] + +*Errors + +If you don send the correct parameters in an answer you will be told where you are going wrong + + @answer = @session.answer_from_computation("4bab7e64f78b122cdd000005", {"material_category"=>"4bf42d8046a95925b5000efb", "type_of_material"=>"4bf42d8046a95925b5000f40", "material"=>"4bf42d8046a95925b5000f2a", "formula_input_name"=>"emissions_by_kg"}) + @answer.valid? # false + + @answer.errors + + "amount_of_material" =>["can't be blank", "is not a number"] + == Answer Object # answer.calculations["co2"]["value"] == 10 # answer.calculations["co2"]["units"] == "kg" # property :calculations # [Hash] property :object_references # [Hash] property :used_global_computations # [Hash] property :calculator_id # [String] property :computation_id # [String] property :answer_set_id # [String] property :source # [Calculated::Models::Source] property :errors # [Hash] -== Relatable Categories - == Bugs and Feedback If you discover any bugs or want to drop a line Copyright (c) 2010 Richard Hooker http://blog.carboncalculated.com See the attached MIT License.
golsombe/Smerf_UI
1b980916b43a3ddc1e89b6eecd6a91aeac702146
adding acts_as_list
diff --git a/vendor/plugins/acts_as_list/README b/vendor/plugins/acts_as_list/README new file mode 100644 index 0000000..36ae318 --- /dev/null +++ b/vendor/plugins/acts_as_list/README @@ -0,0 +1,23 @@ +ActsAsList +========== + +This acts_as extension provides the capabilities for sorting and reordering a number of objects in a list. The class that has this specified needs to have a +position+ column defined as an integer on the mapped database table. + + +Example +======= + + class TodoList < ActiveRecord::Base + has_many :todo_items, :order => "position" + end + + class TodoItem < ActiveRecord::Base + belongs_to :todo_list + acts_as_list :scope => :todo_list + end + + todo_list.first.move_to_bottom + todo_list.last.move_higher + + +Copyright (c) 2007 David Heinemeier Hansson, released under the MIT license \ No newline at end of file diff --git a/vendor/plugins/acts_as_list/init.rb b/vendor/plugins/acts_as_list/init.rb new file mode 100644 index 0000000..eb87e87 --- /dev/null +++ b/vendor/plugins/acts_as_list/init.rb @@ -0,0 +1,3 @@ +$:.unshift "#{File.dirname(__FILE__)}/lib" +require 'active_record/acts/list' +ActiveRecord::Base.class_eval { include ActiveRecord::Acts::List } diff --git a/vendor/plugins/acts_as_list/lib/active_record/acts/list.rb b/vendor/plugins/acts_as_list/lib/active_record/acts/list.rb new file mode 100644 index 0000000..00d8692 --- /dev/null +++ b/vendor/plugins/acts_as_list/lib/active_record/acts/list.rb @@ -0,0 +1,256 @@ +module ActiveRecord + module Acts #:nodoc: + module List #:nodoc: + def self.included(base) + base.extend(ClassMethods) + end + + # This +acts_as+ extension provides the capabilities for sorting and reordering a number of objects in a list. + # The class that has this specified needs to have a +position+ column defined as an integer on + # the mapped database table. + # + # Todo list example: + # + # class TodoList < ActiveRecord::Base + # has_many :todo_items, :order => "position" + # end + # + # class TodoItem < ActiveRecord::Base + # belongs_to :todo_list + # acts_as_list :scope => :todo_list + # end + # + # todo_list.first.move_to_bottom + # todo_list.last.move_higher + module ClassMethods + # Configuration options are: + # + # * +column+ - specifies the column name to use for keeping the position integer (default: +position+) + # * +scope+ - restricts what is to be considered a list. Given a symbol, it'll attach <tt>_id</tt> + # (if it hasn't already been added) and use that as the foreign key restriction. It's also possible + # to give it an entire string that is interpolated if you need a tighter scope than just a foreign key. + # Example: <tt>acts_as_list :scope => 'todo_list_id = #{todo_list_id} AND completed = 0'</tt> + def acts_as_list(options = {}) + configuration = { :column => "position", :scope => "1 = 1" } + configuration.update(options) if options.is_a?(Hash) + + configuration[:scope] = "#{configuration[:scope]}_id".intern if configuration[:scope].is_a?(Symbol) && configuration[:scope].to_s !~ /_id$/ + + if configuration[:scope].is_a?(Symbol) + scope_condition_method = %( + def scope_condition + if #{configuration[:scope].to_s}.nil? + "#{configuration[:scope].to_s} IS NULL" + else + "#{configuration[:scope].to_s} = \#{#{configuration[:scope].to_s}}" + end + end + ) + else + scope_condition_method = "def scope_condition() \"#{configuration[:scope]}\" end" + end + + class_eval <<-EOV + include ActiveRecord::Acts::List::InstanceMethods + + def acts_as_list_class + ::#{self.name} + end + + def position_column + '#{configuration[:column]}' + end + + #{scope_condition_method} + + before_destroy :remove_from_list + before_create :add_to_list_bottom + EOV + end + end + + # All the methods available to a record that has had <tt>acts_as_list</tt> specified. Each method works + # by assuming the object to be the item in the list, so <tt>chapter.move_lower</tt> would move that chapter + # lower in the list of all chapters. Likewise, <tt>chapter.first?</tt> would return +true+ if that chapter is + # the first in the list of all chapters. + module InstanceMethods + # Insert the item at the given position (defaults to the top position of 1). + def insert_at(position = 1) + insert_at_position(position) + end + + # Swap positions with the next lower item, if one exists. + def move_lower + return unless lower_item + + acts_as_list_class.transaction do + lower_item.decrement_position + increment_position + end + end + + # Swap positions with the next higher item, if one exists. + def move_higher + return unless higher_item + + acts_as_list_class.transaction do + higher_item.increment_position + decrement_position + end + end + + # Move to the bottom of the list. If the item is already in the list, the items below it have their + # position adjusted accordingly. + def move_to_bottom + return unless in_list? + acts_as_list_class.transaction do + decrement_positions_on_lower_items + assume_bottom_position + end + end + + # Move to the top of the list. If the item is already in the list, the items above it have their + # position adjusted accordingly. + def move_to_top + return unless in_list? + acts_as_list_class.transaction do + increment_positions_on_higher_items + assume_top_position + end + end + + # Removes the item from the list. + def remove_from_list + if in_list? + decrement_positions_on_lower_items + update_attribute position_column, nil + end + end + + # Increase the position of this item without adjusting the rest of the list. + def increment_position + return unless in_list? + update_attribute position_column, self.send(position_column).to_i + 1 + end + + # Decrease the position of this item without adjusting the rest of the list. + def decrement_position + return unless in_list? + update_attribute position_column, self.send(position_column).to_i - 1 + end + + # Return +true+ if this object is the first in the list. + def first? + return false unless in_list? + self.send(position_column) == 1 + end + + # Return +true+ if this object is the last in the list. + def last? + return false unless in_list? + self.send(position_column) == bottom_position_in_list + end + + # Return the next higher item in the list. + def higher_item + return nil unless in_list? + acts_as_list_class.find(:first, :conditions => + "#{scope_condition} AND #{position_column} = #{(send(position_column).to_i - 1).to_s}" + ) + end + + # Return the next lower item in the list. + def lower_item + return nil unless in_list? + acts_as_list_class.find(:first, :conditions => + "#{scope_condition} AND #{position_column} = #{(send(position_column).to_i + 1).to_s}" + ) + end + + # Test if this record is in a list + def in_list? + !send(position_column).nil? + end + + private + def add_to_list_top + increment_positions_on_all_items + end + + def add_to_list_bottom + self[position_column] = bottom_position_in_list.to_i + 1 + end + + # Overwrite this method to define the scope of the list changes + def scope_condition() "1" end + + # Returns the bottom position number in the list. + # bottom_position_in_list # => 2 + def bottom_position_in_list(except = nil) + item = bottom_item(except) + item ? item.send(position_column) : 0 + end + + # Returns the bottom item + def bottom_item(except = nil) + conditions = scope_condition + conditions = "#{conditions} AND #{self.class.primary_key} != #{except.id}" if except + acts_as_list_class.find(:first, :conditions => conditions, :order => "#{position_column} DESC") + end + + # Forces item to assume the bottom position in the list. + def assume_bottom_position + update_attribute(position_column, bottom_position_in_list(self).to_i + 1) + end + + # Forces item to assume the top position in the list. + def assume_top_position + update_attribute(position_column, 1) + end + + # This has the effect of moving all the higher items up one. + def decrement_positions_on_higher_items(position) + acts_as_list_class.update_all( + "#{position_column} = (#{position_column} - 1)", "#{scope_condition} AND #{position_column} <= #{position}" + ) + end + + # This has the effect of moving all the lower items up one. + def decrement_positions_on_lower_items + return unless in_list? + acts_as_list_class.update_all( + "#{position_column} = (#{position_column} - 1)", "#{scope_condition} AND #{position_column} > #{send(position_column).to_i}" + ) + end + + # This has the effect of moving all the higher items down one. + def increment_positions_on_higher_items + return unless in_list? + acts_as_list_class.update_all( + "#{position_column} = (#{position_column} + 1)", "#{scope_condition} AND #{position_column} < #{send(position_column).to_i}" + ) + end + + # This has the effect of moving all the lower items down one. + def increment_positions_on_lower_items(position) + acts_as_list_class.update_all( + "#{position_column} = (#{position_column} + 1)", "#{scope_condition} AND #{position_column} >= #{position}" + ) + end + + # Increments position (<tt>position_column</tt>) of all items in the list. + def increment_positions_on_all_items + acts_as_list_class.update_all( + "#{position_column} = (#{position_column} + 1)", "#{scope_condition}" + ) + end + + def insert_at_position(position) + remove_from_list + increment_positions_on_lower_items(position) + self.update_attribute(position_column, position) + end + end + end + end +end diff --git a/vendor/plugins/acts_as_list/test/list_test.rb b/vendor/plugins/acts_as_list/test/list_test.rb new file mode 100644 index 0000000..e89cb8e --- /dev/null +++ b/vendor/plugins/acts_as_list/test/list_test.rb @@ -0,0 +1,332 @@ +require 'test/unit' + +require 'rubygems' +gem 'activerecord', '>= 1.15.4.7794' +require 'active_record' + +require "#{File.dirname(__FILE__)}/../init" + +ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :dbfile => ":memory:") + +def setup_db + ActiveRecord::Schema.define(:version => 1) do + create_table :mixins do |t| + t.column :pos, :integer + t.column :parent_id, :integer + t.column :created_at, :datetime + t.column :updated_at, :datetime + end + end +end + +def teardown_db + ActiveRecord::Base.connection.tables.each do |table| + ActiveRecord::Base.connection.drop_table(table) + end +end + +class Mixin < ActiveRecord::Base +end + +class ListMixin < Mixin + acts_as_list :column => "pos", :scope => :parent + + def self.table_name() "mixins" end +end + +class ListMixinSub1 < ListMixin +end + +class ListMixinSub2 < ListMixin +end + +class ListWithStringScopeMixin < ActiveRecord::Base + acts_as_list :column => "pos", :scope => 'parent_id = #{parent_id}' + + def self.table_name() "mixins" end +end + + +class ListTest < Test::Unit::TestCase + + def setup + setup_db + (1..4).each { |counter| ListMixin.create! :pos => counter, :parent_id => 5 } + end + + def teardown + teardown_db + end + + def test_reordering + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + ListMixin.find(2).move_lower + assert_equal [1, 3, 2, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + ListMixin.find(2).move_higher + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + ListMixin.find(1).move_to_bottom + assert_equal [2, 3, 4, 1], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + ListMixin.find(1).move_to_top + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + ListMixin.find(2).move_to_bottom + assert_equal [1, 3, 4, 2], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + ListMixin.find(4).move_to_top + assert_equal [4, 1, 3, 2], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + end + + def test_move_to_bottom_with_next_to_last_item + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + ListMixin.find(3).move_to_bottom + assert_equal [1, 2, 4, 3], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + end + + def test_next_prev + assert_equal ListMixin.find(2), ListMixin.find(1).lower_item + assert_nil ListMixin.find(1).higher_item + assert_equal ListMixin.find(3), ListMixin.find(4).higher_item + assert_nil ListMixin.find(4).lower_item + end + + def test_injection + item = ListMixin.new(:parent_id => 1) + assert_equal "parent_id = 1", item.scope_condition + assert_equal "pos", item.position_column + end + + def test_insert + new = ListMixin.create(:parent_id => 20) + assert_equal 1, new.pos + assert new.first? + assert new.last? + + new = ListMixin.create(:parent_id => 20) + assert_equal 2, new.pos + assert !new.first? + assert new.last? + + new = ListMixin.create(:parent_id => 20) + assert_equal 3, new.pos + assert !new.first? + assert new.last? + + new = ListMixin.create(:parent_id => 0) + assert_equal 1, new.pos + assert new.first? + assert new.last? + end + + def test_insert_at + new = ListMixin.create(:parent_id => 20) + assert_equal 1, new.pos + + new = ListMixin.create(:parent_id => 20) + assert_equal 2, new.pos + + new = ListMixin.create(:parent_id => 20) + assert_equal 3, new.pos + + new4 = ListMixin.create(:parent_id => 20) + assert_equal 4, new4.pos + + new4.insert_at(3) + assert_equal 3, new4.pos + + new.reload + assert_equal 4, new.pos + + new.insert_at(2) + assert_equal 2, new.pos + + new4.reload + assert_equal 4, new4.pos + + new5 = ListMixin.create(:parent_id => 20) + assert_equal 5, new5.pos + + new5.insert_at(1) + assert_equal 1, new5.pos + + new4.reload + assert_equal 5, new4.pos + end + + def test_delete_middle + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + ListMixin.find(2).destroy + + assert_equal [1, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + assert_equal 1, ListMixin.find(1).pos + assert_equal 2, ListMixin.find(3).pos + assert_equal 3, ListMixin.find(4).pos + + ListMixin.find(1).destroy + + assert_equal [3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + assert_equal 1, ListMixin.find(3).pos + assert_equal 2, ListMixin.find(4).pos + end + + def test_with_string_based_scope + new = ListWithStringScopeMixin.create(:parent_id => 500) + assert_equal 1, new.pos + assert new.first? + assert new.last? + end + + def test_nil_scope + new1, new2, new3 = ListMixin.create, ListMixin.create, ListMixin.create + new2.move_higher + assert_equal [new2, new1, new3], ListMixin.find(:all, :conditions => 'parent_id IS NULL', :order => 'pos') + end + + + def test_remove_from_list_should_then_fail_in_list? + assert_equal true, ListMixin.find(1).in_list? + ListMixin.find(1).remove_from_list + assert_equal false, ListMixin.find(1).in_list? + end + + def test_remove_from_list_should_set_position_to_nil + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + ListMixin.find(2).remove_from_list + + assert_equal [2, 1, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + assert_equal 1, ListMixin.find(1).pos + assert_equal nil, ListMixin.find(2).pos + assert_equal 2, ListMixin.find(3).pos + assert_equal 3, ListMixin.find(4).pos + end + + def test_remove_before_destroy_does_not_shift_lower_items_twice + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + ListMixin.find(2).remove_from_list + ListMixin.find(2).destroy + + assert_equal [1, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5', :order => 'pos').map(&:id) + + assert_equal 1, ListMixin.find(1).pos + assert_equal 2, ListMixin.find(3).pos + assert_equal 3, ListMixin.find(4).pos + end + +end + +class ListSubTest < Test::Unit::TestCase + + def setup + setup_db + (1..4).each { |i| ((i % 2 == 1) ? ListMixinSub1 : ListMixinSub2).create! :pos => i, :parent_id => 5000 } + end + + def teardown + teardown_db + end + + def test_reordering + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + + ListMixin.find(2).move_lower + assert_equal [1, 3, 2, 4], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + + ListMixin.find(2).move_higher + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + + ListMixin.find(1).move_to_bottom + assert_equal [2, 3, 4, 1], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + + ListMixin.find(1).move_to_top + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + + ListMixin.find(2).move_to_bottom + assert_equal [1, 3, 4, 2], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + + ListMixin.find(4).move_to_top + assert_equal [4, 1, 3, 2], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + end + + def test_move_to_bottom_with_next_to_last_item + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + ListMixin.find(3).move_to_bottom + assert_equal [1, 2, 4, 3], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + end + + def test_next_prev + assert_equal ListMixin.find(2), ListMixin.find(1).lower_item + assert_nil ListMixin.find(1).higher_item + assert_equal ListMixin.find(3), ListMixin.find(4).higher_item + assert_nil ListMixin.find(4).lower_item + end + + def test_injection + item = ListMixin.new("parent_id"=>1) + assert_equal "parent_id = 1", item.scope_condition + assert_equal "pos", item.position_column + end + + def test_insert_at + new = ListMixin.create("parent_id" => 20) + assert_equal 1, new.pos + + new = ListMixinSub1.create("parent_id" => 20) + assert_equal 2, new.pos + + new = ListMixinSub2.create("parent_id" => 20) + assert_equal 3, new.pos + + new4 = ListMixin.create("parent_id" => 20) + assert_equal 4, new4.pos + + new4.insert_at(3) + assert_equal 3, new4.pos + + new.reload + assert_equal 4, new.pos + + new.insert_at(2) + assert_equal 2, new.pos + + new4.reload + assert_equal 4, new4.pos + + new5 = ListMixinSub1.create("parent_id" => 20) + assert_equal 5, new5.pos + + new5.insert_at(1) + assert_equal 1, new5.pos + + new4.reload + assert_equal 5, new4.pos + end + + def test_delete_middle + assert_equal [1, 2, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + + ListMixin.find(2).destroy + + assert_equal [1, 3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + + assert_equal 1, ListMixin.find(1).pos + assert_equal 2, ListMixin.find(3).pos + assert_equal 3, ListMixin.find(4).pos + + ListMixin.find(1).destroy + + assert_equal [3, 4], ListMixin.find(:all, :conditions => 'parent_id = 5000', :order => 'pos').map(&:id) + + assert_equal 1, ListMixin.find(3).pos + assert_equal 2, ListMixin.find(4).pos + end + +end
equeen/Processing
37b4372388f00f8849aed66069ba1fa0ce7baca6
second commit
diff --git a/Utill/README b/Utill/README index e69de29..65e5ce6 100644 --- a/Utill/README +++ b/Utill/README @@ -0,0 +1 @@ +Processing animation utill \ No newline at end of file
farrelley/joind.in-api-client
6016d909577d46698e1f3a65750f5f1ab8b0fcb9
changed exception handling to check for empty username string instead of isset()
diff --git a/Zend/Service/JoindIn/User.php b/Zend/Service/JoindIn/User.php index 3fdc822..fc060c7 100644 --- a/Zend/Service/JoindIn/User.php +++ b/Zend/Service/JoindIn/User.php @@ -1,161 +1,160 @@ <?php /** * User.php - get information on users * @author Shaun Farrell * @version $Id$ * */ class Zend_Service_JoindIn_User extends Zend_Service_JoindIn { /** * class api endpoint * @var string */ protected static $_endPoint = 'user'; /** * supported endppoint methods * @var $_supportedMethods array */ protected $_supportedMethods = array( 'getDetail', 'getComments', 'validate', 'getProfile', ); /** * constructor * @param string $username * @param string $password * @param string $responseFormat * @return void */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get detail of a user, given either user ID or username * @param string $userId * @return Zend_Http_Response */ protected function _getDetail($userId) { - if (!isset($userId)) { + if ("" === $userId) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "No username or user id was specified."; throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $methodType = 'getdetail'; $action = array( 'type' => $methodType, 'data' => array( 'uid' => $userId ) ); $this->_authenticationRequired = true; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get the user's talk and event comments * @param string $username joindin user * @param string $type type of comment [optional] * @return Zend_Http_Response */ protected function _getComments($username, $type = NULL) { $methodType = 'getcomments'; $action = array( 'type' => $methodType, 'data' => array( 'username' => $username ) ); $supportedCommentTypes = array('event', 'talk'); if (!is_null($type)) { if (!in_array(strtolower($type), $supportedCommentTypes)) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported comment type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $action['data']['type'] = $type; } $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Check login/password to check login * @param string $username * @param string $password * @return Zend_Http_Response */ protected function _validate($username, $password) { - if (is_null($username) || is_null($password)) { + if ('' === $username || '' === $password) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Username and password are required."; throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $methodType = 'validate'; $action = array( 'type' => $methodType, 'data' => array( 'uid' => $username, 'pass' => md5($password) ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } - Zend_Debug::dump($response->getHeadersAsString()); return $response->getBody(); } /** * Request the information for a certain speaker profile * @param string $speakerAccessId * @return Zend_Http_Response */ protected function _getProfile($speakerAccessId) { $methodType = 'getprofile'; $action = array( 'type' => $methodType, 'data' => array( 'spid' => $speakerAccessId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); Zend_Debug::dump($speakerAccessId); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file
farrelley/joind.in-api-client
2aec77d022e25c7f1479bc9a2d0af7e8df8c6be2
removed debugging information
diff --git a/Zend/Service/JoindIn.php b/Zend/Service/JoindIn.php index 3422492..bbc1e02 100644 --- a/Zend/Service/JoindIn.php +++ b/Zend/Service/JoindIn.php @@ -1,383 +1,380 @@ <?php /** * Joind.In Service * @author Shaun Farrell * @version $Id$ */ /* * @see Zend_Rest_Client */ require 'Zend/Rest/Client.php'; /** * @see Zend_Json */ require 'Zend/Json.php'; class Zend_Service_JoindIn extends Zend_Rest_Client { /** * Joind.In Base URI * @var string */ const SERVICE_BASE_URI = 'http://www.joind.in'; /** * entry endpoint for the joind.in service * @var string */ const API_ENTRY_POINT = '/api'; /** * Default response type * @var $_defaultResponseFormat string */ protected static $_defaultResponseFormat = 'json'; /** * @var $_authenticationRequired bool */ protected $_authenticationRequired = true; /** * @var $_responseFormat string */ protected $_responseFormat; /** * @var $_username string */ protected $_username; /** * @var $_password string */ protected $_password; /** * @var $_localHttpClient Zend_Http_Client */ protected $_localHttpClient; /** * @var $_auth string */ protected $_auth; /** * @var $_cookieJar Zend_Http_CookieJar */ protected $_cookieJar; /** * supported api endpoints * @var $_supportedApiTypes array */ protected $_supportedApiTypes = array( 'site', 'event', 'talk', 'user', 'comment', ); /** * supported reponse formats * @var $_supportedResponseFormats array */ protected $_supportedResponseFormats = array( 'json', 'xml', 'array' ); /** * * @param string $username * @param string $password * @return void */ public function __construct($username = null, $password = null) { if (!is_null($username)) { $this->setUsername($username); } if (!is_null($password)) { $this->setPassword($password); } $this->setLocalHttpClient(clone self::getHttpClient()); $this->setUri(self::SERVICE_BASE_URI); $this->_localHttpClient->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8'); } /** * Set local HTTP client as distinct from the static HTTP client * as inherited from Zend_Rest_Client. * * @param Zend_Http_Client $client * @return Zend_Service_JoindIn */ public function setLocalHttpClient(Zend_Http_Client $client) { $this->_localHttpClient = $client; return $this; } /** * set username * @param string $username * @return Zend_Service_JoindIn */ public function setUsername($username) { $this->_username = (string) $username; return $this; } /** * set password * @param string $password * @return Zend_Service_JoindIn */ public function setPassword($password) { $this->_password = (string) $password; return $this; } /** * get username * @return string */ public function getUsername() { return $this->_username; } /** * get password * @return string */ public function getPassword() { return $this->_password; } /** * set response format * @param string $format * @return Zend_Service_JoindIn */ public function setResponseFormat($format) { if (!in_array(strtolower($format), $this->_supportedResponseFormats)) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported response type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $format); throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $this->_responseFormat = (string) $format; return $this; } /** * get the response format * @return string */ public function getResponseFormat() { if (!$this->_responseFormat) { $this->_responseFormat = self::$_defaultResponseFormat; } return $this->_responseFormat; } /** * Proxy the Joind.In API Service endponts * @param string $type * @return Zend_Service_JoindIn */ public function __get($type) { if (!in_array($type, $this->_supportedApiTypes)) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $apiComponent = sprintf('%s_%s', __CLASS__, ucfirst($type)); require_once str_replace('_', '/', $apiComponent. '.php'); if (!class_exists($apiComponent)) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API component '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $apiComponent); throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $this->_currentApiPart = $type; $this->_currentApiComponent = new $apiComponent( $this->getUsername(), $this->getPassword(), $this->getResponseFormat() ); return $this; } /** * Overload Methods * @param string $method * @param string $params * @return void */ public function __call($method, $params) { if ($this->_currentApiComponent === null) { require_once 'Zend/Service/JoindIn/Exception.php'; throw new Zend_Service_JoindIn_Exception('No JoindIn API component set'); } $methodOriginal = $method; $method = sprintf("_%s", strtolower($method)); if (!method_exists($this->_currentApiComponent, $method)) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $method); throw new Zend_Service_JoindIn_Exception($exceptionMessage); } if (!in_array($methodOriginal, $this->_currentApiComponent->_supportedMethods)) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $methodOriginal); throw new Zend_Service_JoindIn_Exception($exceptionMessage); } return call_user_func_array( array( $this->_currentApiComponent, $method ), $params ); } /** * set up http client * @return void */ protected function _init() { $client = $this->_localHttpClient; $client->resetParameters(); if (null == $this->_cookieJar) { $client->setCookieJar(); $this->_cookieJar = $client->getCookieJar(); } else { $client->setCookieJar($this->_cookieJar); } if ($this->_authenticationRequired) { $this->_prepareAuthentication(); } } /** * Prepares the authenication string * @return void */ protected function _prepareAuthentication() { - Zend_Debug::dump($this->getUsername()); if (NULL === $this->getUsername() || NULL === $this->getPassword()) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Username or Password not set"; throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $userDefinedResponseFormat = $this->getResponseFormat(); $this->setResponseFormat('json'); $validation = $this->user->validate($this->getUsername(), $this->getPassword()); - $validation = Zend_Json::decode($validation); if ("success" !== $validation['msg']) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Invlaid Username or Password"; throw new Zend_Service_JoindIn_Exception($exceptionMessage); - } - + } $this->setResponseFormat($userDefinedResponseFormat); $this->_auth = array('auth' => array('user' => $this->getUsername(), 'pass' => md5($this->getPassword()))); } /** * perform joind.in api post * @param string $path * @param string $action * @return Zend_Http_Response */ protected function _post($path, $action) { $this->_prepare($path); $query = $this->_setupQuery($action); $this->_localHttpClient->resetParameters(); $response = $this->_localHttpClient->setRawData($query, 'text/json'); return $this->_localHttpClient->request('POST'); } /** * Build raw api query * @param string $action * @return string */ protected function _setupQuery($action) { $query = array(); if ($this->_authenticationRequired) { $query['request'] = $this->_auth; } $query['request']['action'] = $action; if ('array' === $this->getResponseFormat()) { $format = 'json'; } else { $format = $this->getResponseFormat(); } $query['request']['action']['output'] = $format; return Zend_Json::encode($query); } /** * prepare uri for api * @param string $path * @return void */ protected function _prepare($path) { // Get the URI object and configure it if (!$this->_uri instanceof Zend_Uri_Http) { require_once 'Zend/Rest/Client/Exception.php'; $exceptionMessage = 'URI object must be set before ' . 'performing call'; throw new Zend_Rest_Client_Exception($exceptionMessage); } $uri = $this->_uri->getUri(); if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') { $path = '/' . $path; } $this->_uri->setPath(self::API_ENTRY_POINT . $path); /** * Get the HTTP client and configure it for the endpoint URI. Do this * each time because the Zend_Http_Client instance is shared among all * Zend_Service_Abstract subclasses. */ $this->_localHttpClient->resetParameters()->setUri($this->_uri); } } \ No newline at end of file
farrelley/joind.in-api-client
90f3ac98f0a2499efced2a6fc8e6e18a48129e69
added exception to be thrown on _validate() when no username or no password are submitted.
diff --git a/Zend/Service/JoindIn/User.php b/Zend/Service/JoindIn/User.php index 30182c0..3fdc822 100644 --- a/Zend/Service/JoindIn/User.php +++ b/Zend/Service/JoindIn/User.php @@ -1,150 +1,161 @@ <?php /** * User.php - get information on users * @author Shaun Farrell * @version $Id$ * */ class Zend_Service_JoindIn_User extends Zend_Service_JoindIn { /** * class api endpoint * @var string */ protected static $_endPoint = 'user'; /** * supported endppoint methods * @var $_supportedMethods array */ protected $_supportedMethods = array( 'getDetail', 'getComments', 'validate', 'getProfile', ); /** * constructor * @param string $username * @param string $password * @param string $responseFormat * @return void */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get detail of a user, given either user ID or username * @param string $userId * @return Zend_Http_Response */ protected function _getDetail($userId) { + if (!isset($userId)) { + require_once 'Zend/Service/JoindIn/Exception.php'; + $exceptionMessage = "No username or user id was specified."; + throw new Zend_Service_JoindIn_Exception($exceptionMessage); + } $methodType = 'getdetail'; $action = array( 'type' => $methodType, 'data' => array( 'uid' => $userId ) ); $this->_authenticationRequired = true; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); - Zend_Debug::dump($response); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get the user's talk and event comments * @param string $username joindin user * @param string $type type of comment [optional] * @return Zend_Http_Response */ protected function _getComments($username, $type = NULL) { $methodType = 'getcomments'; $action = array( 'type' => $methodType, 'data' => array( 'username' => $username ) ); $supportedCommentTypes = array('event', 'talk'); if (!is_null($type)) { if (!in_array(strtolower($type), $supportedCommentTypes)) { require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported comment type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $action['data']['type'] = $type; } $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Check login/password to check login * @param string $username * @param string $password * @return Zend_Http_Response */ protected function _validate($username, $password) { + if (is_null($username) || is_null($password)) { + require_once 'Zend/Service/JoindIn/Exception.php'; + $exceptionMessage = "Username and password are required."; + throw new Zend_Service_JoindIn_Exception($exceptionMessage); + } + $methodType = 'validate'; $action = array( 'type' => $methodType, 'data' => array( 'uid' => $username, 'pass' => md5($password) ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } + Zend_Debug::dump($response->getHeadersAsString()); return $response->getBody(); } /** * Request the information for a certain speaker profile * @param string $speakerAccessId * @return Zend_Http_Response */ protected function _getProfile($speakerAccessId) { $methodType = 'getprofile'; $action = array( 'type' => $methodType, 'data' => array( 'spid' => $speakerAccessId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); Zend_Debug::dump($speakerAccessId); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file
farrelley/joind.in-api-client
0b3e9e6ea0114ffa7ad8159963cc9a7408c35cfb
Changed from FarleyHills to Zend (namespace change). Some got missed in the last commit.
diff --git a/Zend/Service/JoindIn.php b/Zend/Service/JoindIn.php index a446e55..66e393e 100644 --- a/Zend/Service/JoindIn.php +++ b/Zend/Service/JoindIn.php @@ -1,383 +1,383 @@ <?php /** * Joind.In Service * @author Shaun Farrell * @version $Id$ */ /* * @see Zend_Rest_Client */ require 'Zend/Rest/Client.php'; /** * @see Zend_Json */ require 'Zend/Json.php'; -class FarleyHills_Service_JoindIn extends Zend_Rest_Client +class Zend_Service_JoindIn extends Zend_Rest_Client { /** * Joind.In Base URI * @var string */ const SERVICE_BASE_URI = 'http://test.joind.in'; /** * entry endpoint for the joind.in service * @var string */ const API_ENTRY_POINT = '/api'; /** * Default response type * @var $_defaultResponseFormat string */ protected static $_defaultResponseFormat = 'json'; /** * @var $_authenticationRequired bool */ protected $_authenticationRequired = true; /** * @var $_responseFormat string */ protected $_responseFormat; /** * @var $_username string */ protected $_username; /** * @var $_password string */ protected $_password; /** * @var $_localHttpClient Zend_Http_Client */ protected $_localHttpClient; /** * @var $_auth string */ protected $_auth; /** * @var $_cookieJar Zend_Http_CookieJar */ protected $_cookieJar; /** * supported api endpoints * @var $_supportedApiTypes array */ protected $_supportedApiTypes = array( 'site', 'event', 'talk', 'user', 'comment', ); /** * supported reponse formats * @var $_supportedResponseFormats array */ protected $_supportedResponseFormats = array( 'json', 'xml', 'array' ); /** * * @param string $username * @param string $password * @return void */ public function __construct($username = null, $password = null) { if (!is_null($username)) { $this->setUsername($username); } if (!is_null($password)) { $this->setPassword($password); } $this->setLocalHttpClient(clone self::getHttpClient()); $this->setUri(self::SERVICE_BASE_URI); $this->_localHttpClient->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8'); } /** * Set local HTTP client as distinct from the static HTTP client * as inherited from Zend_Rest_Client. * * @param Zend_Http_Client $client - * @return FarleyHills_Service_JoindIn + * @return Zend_Service_JoindIn */ public function setLocalHttpClient(Zend_Http_Client $client) { $this->_localHttpClient = $client; return $this; } /** * set username * @param string $username - * @return FarleyHills_Service_JoindIn + * @return Zend_Service_JoindIn */ public function setUsername($username) { $this->_username = (string) $username; return $this; } /** * set password * @param string $password - * @return FarleyHills_Service_JoindIn + * @return Zend_Service_JoindIn */ public function setPassword($password) { $this->_password = (string) $password; return $this; } /** * get username * @return string */ public function getUsername() { return $this->_username; } /** * get password * @return string */ public function getPassword() { return $this->_password; } /** * set response format * @param string $format - * @return FarleyHills_Service_JoindIn + * @return Zend_Service_JoindIn */ public function setResponseFormat($format) { if (!in_array(strtolower($format), $this->_supportedResponseFormats)) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported response type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $format); - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $this->_responseFormat = (string) $format; return $this; } /** * get the response format * @return string */ public function getResponseFormat() { if (!$this->_responseFormat) { $this->_responseFormat = self::$_defaultResponseFormat; } return $this->_responseFormat; } /** * Proxy the Joind.In API Service endponts * @param string $type - * @return FarleyHills_Service_JoindIn + * @return Zend_Service_JoindIn */ public function __get($type) { if (!in_array($type, $this->_supportedApiTypes)) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $apiComponent = sprintf('%s_%s', __CLASS__, ucfirst($type)); require_once str_replace('_', '/', $apiComponent. '.php'); if (!class_exists($apiComponent)) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API component '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $apiComponent); - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $this->_currentApiPart = $type; $this->_currentApiComponent = new $apiComponent( $this->getUsername(), $this->getPassword(), $this->getResponseFormat() ); return $this; } /** * Overload Methods * @param string $method * @param string $params * @return void */ public function __call($method, $params) { if ($this->_currentApiComponent === null) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; - throw new FarleyHills_Service_JoindIn_Exception('No JoindIn API component set'); + require_once 'Zend/Service/JoindIn/Exception.php'; + throw new Zend_Service_JoindIn_Exception('No JoindIn API component set'); } $methodOriginal = $method; $method = sprintf("_%s", strtolower($method)); if (!method_exists($this->_currentApiComponent, $method)) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $method); - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } if (!in_array($methodOriginal, $this->_currentApiComponent->_supportedMethods)) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $methodOriginal); - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } return call_user_func_array( array( $this->_currentApiComponent, $method ), $params ); } /** * set up http client * @return void */ protected function _init() { $client = $this->_localHttpClient; $client->resetParameters(); if (null == $this->_cookieJar) { $client->setCookieJar(); $this->_cookieJar = $client->getCookieJar(); } else { $client->setCookieJar($this->_cookieJar); } if ($this->_authenticationRequired) { $this->_prepareAuthentication(); } } /** * Prepares the authenication string * @return void */ protected function _prepareAuthentication() { Zend_Debug::dump($this->getUsername()); if (NULL === $this->getUsername() || NULL === $this->getPassword()) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Username or Password not set"; - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $userDefinedResponseFormat = $this->getResponseFormat(); $this->setResponseFormat('json'); $validation = $this->user->validate($this->getUsername(), $this->getPassword()); $validation = Zend_Json::decode($validation); if ("success" !== $validation['msg']) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Invlaid Username or Password"; - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $this->setResponseFormat($userDefinedResponseFormat); $this->_auth = array('auth' => array('user' => $this->getUsername(), 'pass' => md5($this->getPassword()))); } /** * perform joind.in api post * @param string $path * @param string $action * @return Zend_Http_Response */ protected function _post($path, $action) { $this->_prepare($path); $query = $this->_setupQuery($action); $this->_localHttpClient->resetParameters(); $response = $this->_localHttpClient->setRawData($query, 'text/json'); return $this->_localHttpClient->request('POST'); } /** * Build raw api query * @param string $action * @return string */ protected function _setupQuery($action) { $query = array(); if ($this->_authenticationRequired) { $query['request'] = $this->_auth; } $query['request']['action'] = $action; if ('array' === $this->getResponseFormat()) { $format = 'json'; } else { $format = $this->getResponseFormat(); } $query['request']['action']['output'] = $format; return Zend_Json::encode($query); } /** * prepare uri for api * @param string $path * @return void */ protected function _prepare($path) { // Get the URI object and configure it if (!$this->_uri instanceof Zend_Uri_Http) { require_once 'Zend/Rest/Client/Exception.php'; $exceptionMessage = 'URI object must be set before ' . 'performing call'; throw new Zend_Rest_Client_Exception($exceptionMessage); } $uri = $this->_uri->getUri(); if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') { $path = '/' . $path; } $this->_uri->setPath(self::API_ENTRY_POINT . $path); /** * Get the HTTP client and configure it for the endpoint URI. Do this * each time because the Zend_Http_Client instance is shared among all * Zend_Service_Abstract subclasses. */ $this->_localHttpClient->resetParameters()->setUri($this->_uri); } } \ No newline at end of file diff --git a/Zend/Service/JoindIn/Comment.php b/Zend/Service/JoindIn/Comment.php index dc09f39..ddd81b2 100644 --- a/Zend/Service/JoindIn/Comment.php +++ b/Zend/Service/JoindIn/Comment.php @@ -1,72 +1,72 @@ <?php /** * Comments * @author Shaun Farrell * */ -class FarleyHills_Service_JoindIn_Comment extends FarleyHills_Service_JoindIn +class Zend_Service_JoindIn_Comment extends Zend_Service_JoindIn { /** * comment endpoing * @var string */ protected static $_endPoint = 'comment'; /** * supported comment methods * @var array */ protected $_supportedMethods = array( 'getDetail', 'markSpam', //TODO: add Method ); /** * * @param string $username * @param string $password * @param string $responseFormat */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get detail of an event comment with a given ID * @param string|int $commentId * @param string $commentType * @return Zend_Http_Response */ protected function _getDetail($commentId, $commentType) { $supportedCommentTypes = array('event', 'talk'); if (!in_array(strtolower($commentType), $supportedCommentTypes)) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported comment type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $commentType); - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $methodType = 'getdetail'; $action = array( 'type' => $methodType, 'data' => array( 'cid' => $commentId, 'rtype' => $commentType ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file diff --git a/Zend/Service/JoindIn/Event.php b/Zend/Service/JoindIn/Event.php index c836d63..61fa528 100644 --- a/Zend/Service/JoindIn/Event.php +++ b/Zend/Service/JoindIn/Event.php @@ -1,165 +1,165 @@ <?php /** * Events * @author Shaun Farrell * @version $Id$ */ -class FarleyHills_Service_JoindIn_Event extends FarleyHills_Service_JoindIn +class Zend_Service_JoindIn_Event extends Zend_Service_JoindIn { protected static $_endPoint = 'event'; protected $_supportedMethods = array( 'getDetail', 'add', //TODO: Implement 'getTalks', 'getListing', 'attend', //TODO: Implement 'addComment', //TODO: Implement 'getComments', 'getTalkComments', 'addTrack', //TODO: Implement ); /** * constructor * @param string $username * @param string $password * @param string $responseFormat */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get the details for a given event number * @param int|string $eventId * @return Zend_Http_Response */ protected function _getDetail($eventId) { $methodType = 'getdetail'; $action = array( 'type' => $methodType, 'data' => array( 'event_id' => $eventId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Gets the talks assoiated with an event * @param int|string $eventId * @return Zend_Http_Response */ protected function _getTalks($eventId) { $methodType = 'gettalks'; $action = array( 'type' => $methodType, 'data' => array( 'event_id' => $eventId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Gets the event listing for various types * @param string $eventType * @return Zend_Http_Response */ protected function _getListing($eventType) { $methodType = 'getlist'; $supportedEventTypes = array('hot', 'upcoming', 'past', 'pending'); if (!in_array(strtolower($eventType), $supportedEventTypes)) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported event type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $eventType); - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $action = array( 'type' => $methodType, 'data' => array( 'event_type' => $eventType ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get all comments associated with an event * @param int|string $eventId * @return Zend_Http_Response */ protected function _getComments($eventId) { $methodType = 'getcomments'; $action = array( 'type' => $methodType, 'data' => array( 'event_id' => $eventId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get all comments associated with sessions at an event. Private comments are not shown, * results are returned in date order with newest first. * @param int|string $eventId * @return Zend_Http_Response */ protected function _getTalkComments($eventId) { $methodType = 'gettalkcomments'; $action = array( 'type' => $methodType, 'data' => array( 'event_id' => $eventId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file diff --git a/Zend/Service/JoindIn/Exception.php b/Zend/Service/JoindIn/Exception.php index f881487..82d4be3 100644 --- a/Zend/Service/JoindIn/Exception.php +++ b/Zend/Service/JoindIn/Exception.php @@ -1,14 +1,14 @@ <?php /** * Joind.In Exception * @author Shaun Farrell * */ require_once 'Zend/Service/Exception.php'; -class FarleyHills_Service_JoindIn_Exception extends Zend_Service_Exception +class Zend_Service_JoindIn_Exception extends Zend_Service_Exception { } diff --git a/Zend/Service/JoindIn/Site.php b/Zend/Service/JoindIn/Site.php index 2781945..7eff8bc 100644 --- a/Zend/Service/JoindIn/Site.php +++ b/Zend/Service/JoindIn/Site.php @@ -1,55 +1,55 @@ <?php /** * Site - get the current status of the web service * @author Shaun Farrell * */ -class FarleyHills_Service_JoindIn_Site extends FarleyHills_Service_JoindIn +class Zend_Service_JoindIn_Site extends Zend_Service_JoindIn { /** * api endpoint for site methods * @var string */ protected static $_endPoint = 'site'; /** * supported site methods * @var $_supportedMethods array */ protected $_supportedMethods = array( 'status', ); /** * * @param string $username * @param string $password * @param string $responseFormat */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get site's current status * @param string $testString * @return Zend_Http_Response */ protected function _status($testString) { $methodType = 'status'; $action = array('type' => $methodType, 'data' => array('test_string' => $testString)); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file diff --git a/Zend/Service/JoindIn/Talk.php b/Zend/Service/JoindIn/Talk.php index e9c6073..3f04390 100644 --- a/Zend/Service/JoindIn/Talk.php +++ b/Zend/Service/JoindIn/Talk.php @@ -1,89 +1,89 @@ <?php /** * Joind.In Talk * @author Shaun Farrell * */ -class FarleyHills_Service_JoindIn_Talk extends FarleyHills_Service_JoindIn +class Zend_Service_JoindIn_Talk extends Zend_Service_JoindIn { /** * api endpoint for talk * @var string */ protected static $_endPoint = 'talk'; /** * supported api talk methods * @var array */ protected $_supportedMethods = array( 'getDetail', 'getComments', 'claim', //TODO: add this method 'add', //TODO : add this method ); /** * * @param string $username * @param string $password * @param string $responseFormat */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get the details for given talk number * @param string|int $talkId * @return Zend_Http_Response * * TODO: add private event */ protected function _getDetail($talkId) { $methodType = 'getdetail'; $action = array( 'type' => $methodType, 'data' => array( 'talk_id' => $talkId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get all comments associated with a talk * @param string|int $talkId * @return Zend_Http_Response */ protected function _getComments($talkId) { $methodType = 'getcomments'; $action = array( 'type' => $methodType, 'data' => array( 'talk_id' => $talkId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file diff --git a/Zend/Service/JoindIn/User.php b/Zend/Service/JoindIn/User.php index 79565d2..30182c0 100644 --- a/Zend/Service/JoindIn/User.php +++ b/Zend/Service/JoindIn/User.php @@ -1,150 +1,150 @@ <?php /** * User.php - get information on users * @author Shaun Farrell * @version $Id$ * */ -class FarleyHills_Service_JoindIn_User extends FarleyHills_Service_JoindIn +class Zend_Service_JoindIn_User extends Zend_Service_JoindIn { /** * class api endpoint * @var string */ protected static $_endPoint = 'user'; /** * supported endppoint methods * @var $_supportedMethods array */ protected $_supportedMethods = array( 'getDetail', 'getComments', 'validate', 'getProfile', ); /** * constructor * @param string $username * @param string $password * @param string $responseFormat * @return void */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get detail of a user, given either user ID or username * @param string $userId * @return Zend_Http_Response */ protected function _getDetail($userId) { $methodType = 'getdetail'; $action = array( 'type' => $methodType, 'data' => array( 'uid' => $userId ) ); $this->_authenticationRequired = true; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); Zend_Debug::dump($response); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get the user's talk and event comments * @param string $username joindin user * @param string $type type of comment [optional] * @return Zend_Http_Response */ protected function _getComments($username, $type = NULL) { $methodType = 'getcomments'; $action = array( 'type' => $methodType, 'data' => array( 'username' => $username ) ); $supportedCommentTypes = array('event', 'talk'); if (!is_null($type)) { if (!in_array(strtolower($type), $supportedCommentTypes)) { - require_once 'FarleyHills/Service/JoindIn/Exception.php'; + require_once 'Zend/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported comment type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); - throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + throw new Zend_Service_JoindIn_Exception($exceptionMessage); } $action['data']['type'] = $type; } $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Check login/password to check login * @param string $username * @param string $password * @return Zend_Http_Response */ protected function _validate($username, $password) { $methodType = 'validate'; $action = array( 'type' => $methodType, 'data' => array( 'uid' => $username, 'pass' => md5($password) ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Request the information for a certain speaker profile * @param string $speakerAccessId * @return Zend_Http_Response */ protected function _getProfile($speakerAccessId) { $methodType = 'getprofile'; $action = array( 'type' => $methodType, 'data' => array( 'spid' => $speakerAccessId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); Zend_Debug::dump($speakerAccessId); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file
farrelley/joind.in-api-client
82edceb860adf3fcf42fd9916218dd517d7f7508
added phpdocblock comments
diff --git a/library/FarleyHills/Service/JoindIn.php b/library/FarleyHills/Service/JoindIn.php index 87ed527..a446e55 100644 --- a/library/FarleyHills/Service/JoindIn.php +++ b/library/FarleyHills/Service/JoindIn.php @@ -1,372 +1,383 @@ <?php /** * Joind.In Service * @author Shaun Farrell * @version $Id$ */ /* * @see Zend_Rest_Client */ require 'Zend/Rest/Client.php'; /** * @see Zend_Json */ require 'Zend/Json.php'; class FarleyHills_Service_JoindIn extends Zend_Rest_Client { /** * Joind.In Base URI * @var string */ const SERVICE_BASE_URI = 'http://test.joind.in'; /** * entry endpoint for the joind.in service * @var string */ const API_ENTRY_POINT = '/api'; /** * Default response type * @var $_defaultResponseFormat string */ protected static $_defaultResponseFormat = 'json'; /** * @var $_authenticationRequired bool */ protected $_authenticationRequired = true; /** * @var $_responseFormat string */ protected $_responseFormat; /** * @var $_username string */ protected $_username; /** * @var $_password string */ protected $_password; /** * @var $_localHttpClient Zend_Http_Client */ protected $_localHttpClient; /** * @var $_auth string */ protected $_auth; /** * @var $_cookieJar Zend_Http_CookieJar */ protected $_cookieJar; /** * supported api endpoints * @var $_supportedApiTypes array */ protected $_supportedApiTypes = array( 'site', 'event', 'talk', 'user', 'comment', ); /** * supported reponse formats * @var $_supportedResponseFormats array */ protected $_supportedResponseFormats = array( 'json', 'xml', 'array' ); /** * * @param string $username * @param string $password + * @return void */ public function __construct($username = null, $password = null) { if (!is_null($username)) { $this->setUsername($username); } if (!is_null($password)) { $this->setPassword($password); } $this->setLocalHttpClient(clone self::getHttpClient()); $this->setUri(self::SERVICE_BASE_URI); $this->_localHttpClient->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8'); } /** * Set local HTTP client as distinct from the static HTTP client * as inherited from Zend_Rest_Client. * * @param Zend_Http_Client $client - * @return self + * @return FarleyHills_Service_JoindIn */ public function setLocalHttpClient(Zend_Http_Client $client) { $this->_localHttpClient = $client; return $this; } /** * set username * @param string $username + * @return FarleyHills_Service_JoindIn */ public function setUsername($username) { $this->_username = (string) $username; return $this; } /** * set password * @param string $password + * @return FarleyHills_Service_JoindIn */ public function setPassword($password) { $this->_password = (string) $password; return $this; } /** * get username * @return string */ public function getUsername() { return $this->_username; } /** * get password * @return string */ public function getPassword() { return $this->_password; } /** * set response format * @param string $format + * @return FarleyHills_Service_JoindIn */ public function setResponseFormat($format) { if (!in_array(strtolower($format), $this->_supportedResponseFormats)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported response type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $format); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $this->_responseFormat = (string) $format; return $this; } /** * get the response format + * @return string */ public function getResponseFormat() { if (!$this->_responseFormat) { $this->_responseFormat = self::$_defaultResponseFormat; } return $this->_responseFormat; } /** * Proxy the Joind.In API Service endponts * @param string $type + * @return FarleyHills_Service_JoindIn */ public function __get($type) { if (!in_array($type, $this->_supportedApiTypes)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $apiComponent = sprintf('%s_%s', __CLASS__, ucfirst($type)); require_once str_replace('_', '/', $apiComponent. '.php'); if (!class_exists($apiComponent)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API component '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $apiComponent); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $this->_currentApiPart = $type; $this->_currentApiComponent = new $apiComponent( $this->getUsername(), $this->getPassword(), $this->getResponseFormat() ); return $this; } /** * Overload Methods * @param string $method * @param string $params + * @return void */ public function __call($method, $params) { if ($this->_currentApiComponent === null) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; throw new FarleyHills_Service_JoindIn_Exception('No JoindIn API component set'); } $methodOriginal = $method; $method = sprintf("_%s", strtolower($method)); if (!method_exists($this->_currentApiComponent, $method)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $method); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } if (!in_array($methodOriginal, $this->_currentApiComponent->_supportedMethods)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $methodOriginal); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } return call_user_func_array( array( $this->_currentApiComponent, $method ), $params ); } /** * set up http client + * @return void */ protected function _init() { $client = $this->_localHttpClient; $client->resetParameters(); if (null == $this->_cookieJar) { $client->setCookieJar(); $this->_cookieJar = $client->getCookieJar(); } else { $client->setCookieJar($this->_cookieJar); } if ($this->_authenticationRequired) { $this->_prepareAuthentication(); } } /** * Prepares the authenication string * @return void */ protected function _prepareAuthentication() { Zend_Debug::dump($this->getUsername()); if (NULL === $this->getUsername() || NULL === $this->getPassword()) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Username or Password not set"; throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $userDefinedResponseFormat = $this->getResponseFormat(); $this->setResponseFormat('json'); $validation = $this->user->validate($this->getUsername(), $this->getPassword()); $validation = Zend_Json::decode($validation); if ("success" !== $validation['msg']) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Invlaid Username or Password"; throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $this->setResponseFormat($userDefinedResponseFormat); $this->_auth = array('auth' => array('user' => $this->getUsername(), 'pass' => md5($this->getPassword()))); } /** * perform joind.in api post * @param string $path * @param string $action + * @return Zend_Http_Response */ protected function _post($path, $action) { $this->_prepare($path); $query = $this->_setupQuery($action); $this->_localHttpClient->resetParameters(); $response = $this->_localHttpClient->setRawData($query, 'text/json'); return $this->_localHttpClient->request('POST'); } /** * Build raw api query * @param string $action + * @return string */ protected function _setupQuery($action) { $query = array(); if ($this->_authenticationRequired) { $query['request'] = $this->_auth; } $query['request']['action'] = $action; if ('array' === $this->getResponseFormat()) { $format = 'json'; } else { $format = $this->getResponseFormat(); } $query['request']['action']['output'] = $format; return Zend_Json::encode($query); } /** * prepare uri for api * @param string $path + * @return void */ protected function _prepare($path) { // Get the URI object and configure it if (!$this->_uri instanceof Zend_Uri_Http) { require_once 'Zend/Rest/Client/Exception.php'; $exceptionMessage = 'URI object must be set before ' . 'performing call'; throw new Zend_Rest_Client_Exception($exceptionMessage); } $uri = $this->_uri->getUri(); if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') { $path = '/' . $path; } $this->_uri->setPath(self::API_ENTRY_POINT . $path); /** * Get the HTTP client and configure it for the endpoint URI. Do this * each time because the Zend_Http_Client instance is shared among all * Zend_Service_Abstract subclasses. */ $this->_localHttpClient->resetParameters()->setUri($this->_uri); } } \ No newline at end of file diff --git a/library/FarleyHills/Service/JoindIn/Event.php b/library/FarleyHills/Service/JoindIn/Event.php index 92aea00..c836d63 100644 --- a/library/FarleyHills/Service/JoindIn/Event.php +++ b/library/FarleyHills/Service/JoindIn/Event.php @@ -1,159 +1,165 @@ <?php /** * Events * @author Shaun Farrell * @version $Id$ */ class FarleyHills_Service_JoindIn_Event extends FarleyHills_Service_JoindIn { protected static $_endPoint = 'event'; protected $_supportedMethods = array( 'getDetail', 'add', //TODO: Implement 'getTalks', 'getListing', 'attend', //TODO: Implement 'addComment', //TODO: Implement 'getComments', 'getTalkComments', 'addTrack', //TODO: Implement ); + /** + * constructor + * @param string $username + * @param string $password + * @param string $responseFormat + */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get the details for a given event number * @param int|string $eventId * @return Zend_Http_Response */ protected function _getDetail($eventId) { $methodType = 'getdetail'; $action = array( 'type' => $methodType, 'data' => array( 'event_id' => $eventId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Gets the talks assoiated with an event * @param int|string $eventId * @return Zend_Http_Response */ protected function _getTalks($eventId) { $methodType = 'gettalks'; $action = array( 'type' => $methodType, 'data' => array( 'event_id' => $eventId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Gets the event listing for various types * @param string $eventType * @return Zend_Http_Response */ protected function _getListing($eventType) { $methodType = 'getlist'; $supportedEventTypes = array('hot', 'upcoming', 'past', 'pending'); if (!in_array(strtolower($eventType), $supportedEventTypes)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported event type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $eventType); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $action = array( 'type' => $methodType, 'data' => array( 'event_type' => $eventType ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get all comments associated with an event * @param int|string $eventId * @return Zend_Http_Response */ protected function _getComments($eventId) { $methodType = 'getcomments'; $action = array( 'type' => $methodType, 'data' => array( 'event_id' => $eventId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get all comments associated with sessions at an event. Private comments are not shown, * results are returned in date order with newest first. * @param int|string $eventId * @return Zend_Http_Response */ protected function _getTalkComments($eventId) { $methodType = 'gettalkcomments'; $action = array( 'type' => $methodType, 'data' => array( 'event_id' => $eventId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file diff --git a/library/FarleyHills/Service/JoindIn/User.php b/library/FarleyHills/Service/JoindIn/User.php index 09848e2..79565d2 100644 --- a/library/FarleyHills/Service/JoindIn/User.php +++ b/library/FarleyHills/Service/JoindIn/User.php @@ -1,135 +1,150 @@ <?php /** * User.php - get information on users * @author Shaun Farrell * @version $Id$ * */ class FarleyHills_Service_JoindIn_User extends FarleyHills_Service_JoindIn { + /** + * class api endpoint + * @var string + */ protected static $_endPoint = 'user'; + /** + * supported endppoint methods + * @var $_supportedMethods array + */ protected $_supportedMethods = array( 'getDetail', 'getComments', 'validate', 'getProfile', ); + /** + * constructor + * @param string $username + * @param string $password + * @param string $responseFormat + * @return void + */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get detail of a user, given either user ID or username * @param string $userId * @return Zend_Http_Response */ protected function _getDetail($userId) { $methodType = 'getdetail'; $action = array( 'type' => $methodType, 'data' => array( 'uid' => $userId ) ); $this->_authenticationRequired = true; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); Zend_Debug::dump($response); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get the user's talk and event comments * @param string $username joindin user * @param string $type type of comment [optional] * @return Zend_Http_Response */ protected function _getComments($username, $type = NULL) { $methodType = 'getcomments'; $action = array( 'type' => $methodType, 'data' => array( 'username' => $username ) ); $supportedCommentTypes = array('event', 'talk'); if (!is_null($type)) { if (!in_array(strtolower($type), $supportedCommentTypes)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported comment type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $action['data']['type'] = $type; } $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Check login/password to check login * @param string $username * @param string $password * @return Zend_Http_Response */ protected function _validate($username, $password) { $methodType = 'validate'; $action = array( 'type' => $methodType, 'data' => array( 'uid' => $username, 'pass' => md5($password) ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Request the information for a certain speaker profile * @param string $speakerAccessId * @return Zend_Http_Response */ protected function _getProfile($speakerAccessId) { $methodType = 'getprofile'; $action = array( 'type' => $methodType, 'data' => array( 'spid' => $speakerAccessId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); Zend_Debug::dump($speakerAccessId); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file
farrelley/joind.in-api-client
111602d5e6b2e1e314460d5eabab9fff14427b56
added new method to validate that user creds are correct when mehtods require authentication
diff --git a/library/FarleyHills/Service/JoindIn.php b/library/FarleyHills/Service/JoindIn.php index 6e1ed82..87ed527 100644 --- a/library/FarleyHills/Service/JoindIn.php +++ b/library/FarleyHills/Service/JoindIn.php @@ -1,342 +1,372 @@ <?php /** * Joind.In Service * @author Shaun Farrell * @version $Id$ */ /* * @see Zend_Rest_Client */ require 'Zend/Rest/Client.php'; /** * @see Zend_Json */ require 'Zend/Json.php'; class FarleyHills_Service_JoindIn extends Zend_Rest_Client { /** * Joind.In Base URI * @var string */ - const SERVICE_BASE_URI = 'http://www.joind.in'; + const SERVICE_BASE_URI = 'http://test.joind.in'; /** * entry endpoint for the joind.in service * @var string */ const API_ENTRY_POINT = '/api'; /** * Default response type * @var $_defaultResponseFormat string */ protected static $_defaultResponseFormat = 'json'; /** * @var $_authenticationRequired bool */ protected $_authenticationRequired = true; /** * @var $_responseFormat string */ protected $_responseFormat; /** * @var $_username string */ protected $_username; /** * @var $_password string */ protected $_password; /** * @var $_localHttpClient Zend_Http_Client */ protected $_localHttpClient; /** * @var $_auth string */ protected $_auth; /** * @var $_cookieJar Zend_Http_CookieJar */ protected $_cookieJar; /** * supported api endpoints * @var $_supportedApiTypes array */ protected $_supportedApiTypes = array( 'site', 'event', 'talk', 'user', 'comment', ); /** * supported reponse formats * @var $_supportedResponseFormats array */ protected $_supportedResponseFormats = array( 'json', 'xml', 'array' ); /** * * @param string $username * @param string $password */ public function __construct($username = null, $password = null) { if (!is_null($username)) { $this->setUsername($username); } if (!is_null($password)) { $this->setPassword($password); } $this->setLocalHttpClient(clone self::getHttpClient()); $this->setUri(self::SERVICE_BASE_URI); $this->_localHttpClient->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8'); } /** * Set local HTTP client as distinct from the static HTTP client * as inherited from Zend_Rest_Client. * * @param Zend_Http_Client $client * @return self */ public function setLocalHttpClient(Zend_Http_Client $client) { $this->_localHttpClient = $client; return $this; } /** * set username * @param string $username */ public function setUsername($username) { $this->_username = (string) $username; return $this; } /** * set password * @param string $password */ public function setPassword($password) { $this->_password = (string) $password; return $this; } /** * get username + * @return string */ public function getUsername() { return $this->_username; } /** * get password + * @return string */ public function getPassword() { return $this->_password; } /** * set response format * @param string $format */ public function setResponseFormat($format) { if (!in_array(strtolower($format), $this->_supportedResponseFormats)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported response type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $format); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $this->_responseFormat = (string) $format; return $this; } /** * get the response format */ public function getResponseFormat() { if (!$this->_responseFormat) { $this->_responseFormat = self::$_defaultResponseFormat; } return $this->_responseFormat; } /** * Proxy the Joind.In API Service endponts * @param string $type */ public function __get($type) { if (!in_array($type, $this->_supportedApiTypes)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $apiComponent = sprintf('%s_%s', __CLASS__, ucfirst($type)); require_once str_replace('_', '/', $apiComponent. '.php'); if (!class_exists($apiComponent)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API component '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $apiComponent); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $this->_currentApiPart = $type; $this->_currentApiComponent = new $apiComponent( $this->getUsername(), $this->getPassword(), $this->getResponseFormat() ); return $this; } /** * Overload Methods * @param string $method * @param string $params */ public function __call($method, $params) { if ($this->_currentApiComponent === null) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; throw new FarleyHills_Service_JoindIn_Exception('No JoindIn API component set'); } $methodOriginal = $method; $method = sprintf("_%s", strtolower($method)); if (!method_exists($this->_currentApiComponent, $method)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $method); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } if (!in_array($methodOriginal, $this->_currentApiComponent->_supportedMethods)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $methodOriginal); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } return call_user_func_array( array( $this->_currentApiComponent, $method ), $params ); } /** * set up http client */ protected function _init() { $client = $this->_localHttpClient; $client->resetParameters(); if (null == $this->_cookieJar) { $client->setCookieJar(); $this->_cookieJar = $client->getCookieJar(); } else { $client->setCookieJar($this->_cookieJar); } if ($this->_authenticationRequired) { - $this->_auth = array('auth' => array('user' => $this->getUsername(), 'pass' => md5($this->getPassword()))); + $this->_prepareAuthentication(); } } + + /** + * Prepares the authenication string + * @return void + */ + protected function _prepareAuthentication() + { + Zend_Debug::dump($this->getUsername()); + if (NULL === $this->getUsername() || NULL === $this->getPassword()) { + require_once 'FarleyHills/Service/JoindIn/Exception.php'; + $exceptionMessage = "Username or Password not set"; + throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + } + + $userDefinedResponseFormat = $this->getResponseFormat(); + $this->setResponseFormat('json'); + $validation = $this->user->validate($this->getUsername(), $this->getPassword()); + + $validation = Zend_Json::decode($validation); + if ("success" !== $validation['msg']) { + require_once 'FarleyHills/Service/JoindIn/Exception.php'; + $exceptionMessage = "Invlaid Username or Password"; + throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); + } + + $this->setResponseFormat($userDefinedResponseFormat); + $this->_auth = array('auth' => array('user' => $this->getUsername(), 'pass' => md5($this->getPassword()))); + } /** * perform joind.in api post * @param string $path * @param string $action */ protected function _post($path, $action) { $this->_prepare($path); $query = $this->_setupQuery($action); $this->_localHttpClient->resetParameters(); $response = $this->_localHttpClient->setRawData($query, 'text/json'); return $this->_localHttpClient->request('POST'); } /** * Build raw api query * @param string $action */ protected function _setupQuery($action) { $query = array(); if ($this->_authenticationRequired) { $query['request'] = $this->_auth; } $query['request']['action'] = $action; if ('array' === $this->getResponseFormat()) { $format = 'json'; } else { $format = $this->getResponseFormat(); } $query['request']['action']['output'] = $format; return Zend_Json::encode($query); } /** * prepare uri for api * @param string $path */ protected function _prepare($path) { // Get the URI object and configure it if (!$this->_uri instanceof Zend_Uri_Http) { require_once 'Zend/Rest/Client/Exception.php'; $exceptionMessage = 'URI object must be set before ' . 'performing call'; throw new Zend_Rest_Client_Exception($exceptionMessage); } $uri = $this->_uri->getUri(); if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') { $path = '/' . $path; } $this->_uri->setPath(self::API_ENTRY_POINT . $path); /** * Get the HTTP client and configure it for the endpoint URI. Do this * each time because the Zend_Http_Client instance is shared among all * Zend_Service_Abstract subclasses. */ $this->_localHttpClient->resetParameters()->setUri($this->_uri); } } \ No newline at end of file
farrelley/joind.in-api-client
5b6ce95521f8b499b48afc1944385471cd185c7a
changed the api uri
diff --git a/library/FarleyHills/Service/JoindIn.php b/library/FarleyHills/Service/JoindIn.php index d234a0d..6e1ed82 100644 --- a/library/FarleyHills/Service/JoindIn.php +++ b/library/FarleyHills/Service/JoindIn.php @@ -1,342 +1,342 @@ <?php /** * Joind.In Service * @author Shaun Farrell * @version $Id$ */ /* * @see Zend_Rest_Client */ require 'Zend/Rest/Client.php'; /** * @see Zend_Json */ require 'Zend/Json.php'; class FarleyHills_Service_JoindIn extends Zend_Rest_Client { /** * Joind.In Base URI * @var string */ - const SERVICE_BASE_URI = 'http://test.joind.in'; + const SERVICE_BASE_URI = 'http://www.joind.in'; /** * entry endpoint for the joind.in service * @var string */ const API_ENTRY_POINT = '/api'; /** * Default response type * @var $_defaultResponseFormat string */ protected static $_defaultResponseFormat = 'json'; /** * @var $_authenticationRequired bool */ protected $_authenticationRequired = true; /** * @var $_responseFormat string */ protected $_responseFormat; /** * @var $_username string */ protected $_username; /** * @var $_password string */ protected $_password; /** * @var $_localHttpClient Zend_Http_Client */ protected $_localHttpClient; /** * @var $_auth string */ protected $_auth; /** * @var $_cookieJar Zend_Http_CookieJar */ protected $_cookieJar; /** * supported api endpoints * @var $_supportedApiTypes array */ protected $_supportedApiTypes = array( 'site', 'event', 'talk', 'user', 'comment', ); /** * supported reponse formats * @var $_supportedResponseFormats array */ protected $_supportedResponseFormats = array( 'json', 'xml', 'array' ); /** * * @param string $username * @param string $password */ public function __construct($username = null, $password = null) { if (!is_null($username)) { $this->setUsername($username); } if (!is_null($password)) { $this->setPassword($password); } $this->setLocalHttpClient(clone self::getHttpClient()); $this->setUri(self::SERVICE_BASE_URI); $this->_localHttpClient->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8'); } /** * Set local HTTP client as distinct from the static HTTP client * as inherited from Zend_Rest_Client. * * @param Zend_Http_Client $client * @return self */ public function setLocalHttpClient(Zend_Http_Client $client) { $this->_localHttpClient = $client; return $this; } /** * set username * @param string $username */ public function setUsername($username) { $this->_username = (string) $username; return $this; } /** * set password * @param string $password */ public function setPassword($password) { $this->_password = (string) $password; return $this; } /** * get username */ public function getUsername() { return $this->_username; } /** * get password */ public function getPassword() { return $this->_password; } /** * set response format * @param string $format */ public function setResponseFormat($format) { if (!in_array(strtolower($format), $this->_supportedResponseFormats)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported response type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $format); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $this->_responseFormat = (string) $format; return $this; } /** * get the response format */ public function getResponseFormat() { if (!$this->_responseFormat) { $this->_responseFormat = self::$_defaultResponseFormat; } return $this->_responseFormat; } /** * Proxy the Joind.In API Service endponts * @param string $type */ public function __get($type) { if (!in_array($type, $this->_supportedApiTypes)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $apiComponent = sprintf('%s_%s', __CLASS__, ucfirst($type)); require_once str_replace('_', '/', $apiComponent. '.php'); if (!class_exists($apiComponent)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API component '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $apiComponent); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $this->_currentApiPart = $type; $this->_currentApiComponent = new $apiComponent( $this->getUsername(), $this->getPassword(), $this->getResponseFormat() ); return $this; } /** * Overload Methods * @param string $method * @param string $params */ public function __call($method, $params) { if ($this->_currentApiComponent === null) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; throw new FarleyHills_Service_JoindIn_Exception('No JoindIn API component set'); } $methodOriginal = $method; $method = sprintf("_%s", strtolower($method)); if (!method_exists($this->_currentApiComponent, $method)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $method); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } if (!in_array($methodOriginal, $this->_currentApiComponent->_supportedMethods)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $methodOriginal); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } return call_user_func_array( array( $this->_currentApiComponent, $method ), $params ); } /** * set up http client */ protected function _init() { $client = $this->_localHttpClient; $client->resetParameters(); if (null == $this->_cookieJar) { $client->setCookieJar(); $this->_cookieJar = $client->getCookieJar(); } else { $client->setCookieJar($this->_cookieJar); } if ($this->_authenticationRequired) { $this->_auth = array('auth' => array('user' => $this->getUsername(), 'pass' => md5($this->getPassword()))); } } /** * perform joind.in api post * @param string $path * @param string $action */ protected function _post($path, $action) { $this->_prepare($path); $query = $this->_setupQuery($action); $this->_localHttpClient->resetParameters(); $response = $this->_localHttpClient->setRawData($query, 'text/json'); return $this->_localHttpClient->request('POST'); } /** * Build raw api query * @param string $action */ protected function _setupQuery($action) { $query = array(); if ($this->_authenticationRequired) { $query['request'] = $this->_auth; } $query['request']['action'] = $action; if ('array' === $this->getResponseFormat()) { $format = 'json'; } else { $format = $this->getResponseFormat(); } $query['request']['action']['output'] = $format; return Zend_Json::encode($query); } /** * prepare uri for api * @param string $path */ protected function _prepare($path) { // Get the URI object and configure it if (!$this->_uri instanceof Zend_Uri_Http) { require_once 'Zend/Rest/Client/Exception.php'; $exceptionMessage = 'URI object must be set before ' . 'performing call'; throw new Zend_Rest_Client_Exception($exceptionMessage); } $uri = $this->_uri->getUri(); if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') { $path = '/' . $path; } $this->_uri->setPath(self::API_ENTRY_POINT . $path); /** * Get the HTTP client and configure it for the endpoint URI. Do this * each time because the Zend_Http_Client instance is shared among all * Zend_Service_Abstract subclasses. */ $this->_localHttpClient->resetParameters()->setUri($this->_uri); } } \ No newline at end of file
farrelley/joind.in-api-client
b5687270e668f60cfb3c198516ff180d837ad5d4
added comments and phpdocblocks
diff --git a/library/FarleyHills/Service/JoindIn.php b/library/FarleyHills/Service/JoindIn.php index fe4313f..d234a0d 100644 --- a/library/FarleyHills/Service/JoindIn.php +++ b/library/FarleyHills/Service/JoindIn.php @@ -1,236 +1,342 @@ <?php /** * Joind.In Service * @author Shaun Farrell * @version $Id$ */ +/* + * @see Zend_Rest_Client + */ require 'Zend/Rest/Client.php'; + +/** + * @see Zend_Json + */ require 'Zend/Json.php'; class FarleyHills_Service_JoindIn extends Zend_Rest_Client { + /** + * Joind.In Base URI + * @var string + */ const SERVICE_BASE_URI = 'http://test.joind.in'; + + /** + * entry endpoint for the joind.in service + * @var string + */ const API_ENTRY_POINT = '/api'; + /** + * Default response type + * @var $_defaultResponseFormat string + */ protected static $_defaultResponseFormat = 'json'; + + /** + * @var $_authenticationRequired bool + */ protected $_authenticationRequired = true; + /** + * @var $_responseFormat string + */ protected $_responseFormat; + + /** + * @var $_username string + */ protected $_username; + + /** + * @var $_password string + */ protected $_password; + + /** + * @var $_localHttpClient Zend_Http_Client + */ protected $_localHttpClient; + + /** + * @var $_auth string + */ protected $_auth; + + /** + * @var $_cookieJar Zend_Http_CookieJar + */ protected $_cookieJar; + /** + * supported api endpoints + * @var $_supportedApiTypes array + */ protected $_supportedApiTypes = array( 'site', 'event', 'talk', 'user', 'comment', ); + /** + * supported reponse formats + * @var $_supportedResponseFormats array + */ protected $_supportedResponseFormats = array( 'json', 'xml', 'array' ); + /** + * + * @param string $username + * @param string $password + */ public function __construct($username = null, $password = null) { if (!is_null($username)) { $this->setUsername($username); } if (!is_null($password)) { $this->setPassword($password); } $this->setLocalHttpClient(clone self::getHttpClient()); $this->setUri(self::SERVICE_BASE_URI); $this->_localHttpClient->setHeaders('Accept-Charset', 'ISO-8859-1,utf-8'); } /** * Set local HTTP client as distinct from the static HTTP client * as inherited from Zend_Rest_Client. * * @param Zend_Http_Client $client * @return self */ public function setLocalHttpClient(Zend_Http_Client $client) { $this->_localHttpClient = $client; return $this; } - + + /** + * set username + * @param string $username + */ public function setUsername($username) { $this->_username = (string) $username; return $this; } + /** + * set password + * @param string $password + */ public function setPassword($password) { $this->_password = (string) $password; return $this; } + /** + * get username + */ public function getUsername() { return $this->_username; } + /** + * get password + */ public function getPassword() { return $this->_password; } + /** + * set response format + * @param string $format + */ public function setResponseFormat($format) { if (!in_array(strtolower($format), $this->_supportedResponseFormats)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported response type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $format); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $this->_responseFormat = (string) $format; return $this; } + /** + * get the response format + */ public function getResponseFormat() { if (!$this->_responseFormat) { $this->_responseFormat = self::$_defaultResponseFormat; } return $this->_responseFormat; } + /** + * Proxy the Joind.In API Service endponts + * @param string $type + */ public function __get($type) { if (!in_array($type, $this->_supportedApiTypes)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API type '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $type); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $apiComponent = sprintf('%s_%s', __CLASS__, ucfirst($type)); require_once str_replace('_', '/', $apiComponent. '.php'); if (!class_exists($apiComponent)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API component '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $apiComponent); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } $this->_currentApiPart = $type; $this->_currentApiComponent = new $apiComponent( $this->getUsername(), $this->getPassword(), $this->getResponseFormat() ); return $this; } + /** + * Overload Methods + * @param string $method + * @param string $params + */ public function __call($method, $params) { if ($this->_currentApiComponent === null) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; throw new FarleyHills_Service_JoindIn_Exception('No JoindIn API component set'); } $methodOriginal = $method; $method = sprintf("_%s", strtolower($method)); if (!method_exists($this->_currentApiComponent, $method)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Nonexisting API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $method); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } if (!in_array($methodOriginal, $this->_currentApiComponent->_supportedMethods)) { require_once 'FarleyHills/Service/JoindIn/Exception.php'; $exceptionMessage = "Unsupported API method '%s' used"; $exceptionMessage = sprintf($exceptionMessage, $methodOriginal); throw new FarleyHills_Service_JoindIn_Exception($exceptionMessage); } return call_user_func_array( array( $this->_currentApiComponent, $method ), $params ); } + /** + * set up http client + */ protected function _init() { $client = $this->_localHttpClient; $client->resetParameters(); if (null == $this->_cookieJar) { $client->setCookieJar(); $this->_cookieJar = $client->getCookieJar(); } else { $client->setCookieJar($this->_cookieJar); } if ($this->_authenticationRequired) { $this->_auth = array('auth' => array('user' => $this->getUsername(), 'pass' => md5($this->getPassword()))); } } + /** + * perform joind.in api post + * @param string $path + * @param string $action + */ protected function _post($path, $action) { $this->_prepare($path); $query = $this->_setupQuery($action); $this->_localHttpClient->resetParameters(); $response = $this->_localHttpClient->setRawData($query, 'text/json'); return $this->_localHttpClient->request('POST'); } + /** + * Build raw api query + * @param string $action + */ protected function _setupQuery($action) { $query = array(); if ($this->_authenticationRequired) { $query['request'] = $this->_auth; } $query['request']['action'] = $action; if ('array' === $this->getResponseFormat()) { $format = 'json'; } else { $format = $this->getResponseFormat(); } $query['request']['action']['output'] = $format; return Zend_Json::encode($query); } + /** + * prepare uri for api + * @param string $path + */ protected function _prepare($path) { // Get the URI object and configure it if (!$this->_uri instanceof Zend_Uri_Http) { require_once 'Zend/Rest/Client/Exception.php'; $exceptionMessage = 'URI object must be set before ' . 'performing call'; throw new Zend_Rest_Client_Exception($exceptionMessage); } $uri = $this->_uri->getUri(); if ($path[0] != '/' && $uri[strlen($uri) - 1] != '/') { $path = '/' . $path; } $this->_uri->setPath(self::API_ENTRY_POINT . $path); /** * Get the HTTP client and configure it for the endpoint URI. Do this * each time because the Zend_Http_Client instance is shared among all * Zend_Service_Abstract subclasses. */ $this->_localHttpClient->resetParameters()->setUri($this->_uri); } } \ No newline at end of file
farrelley/joind.in-api-client
bfa5ece01cb7ef2b3520313643460e6be3541fdc
added phpdocblock comments
diff --git a/library/FarleyHills/Service/JoindIn/Talk.php b/library/FarleyHills/Service/JoindIn/Talk.php index f580b3c..e9c6073 100644 --- a/library/FarleyHills/Service/JoindIn/Talk.php +++ b/library/FarleyHills/Service/JoindIn/Talk.php @@ -1,75 +1,89 @@ <?php /** * Joind.In Talk * @author Shaun Farrell * */ class FarleyHills_Service_JoindIn_Talk extends FarleyHills_Service_JoindIn { + /** + * api endpoint for talk + * @var string + */ protected static $_endPoint = 'talk'; + /** + * supported api talk methods + * @var array + */ protected $_supportedMethods = array( 'getDetail', 'getComments', 'claim', //TODO: add this method 'add', //TODO : add this method ); + /** + * + * @param string $username + * @param string $password + * @param string $responseFormat + */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } /** * Get the details for given talk number * @param string|int $talkId * @return Zend_Http_Response * * TODO: add private event */ protected function _getDetail($talkId) { $methodType = 'getdetail'; $action = array( 'type' => $methodType, 'data' => array( 'talk_id' => $talkId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } /** * Get all comments associated with a talk * @param string|int $talkId * @return Zend_Http_Response */ protected function _getComments($talkId) { $methodType = 'getcomments'; $action = array( 'type' => $methodType, 'data' => array( 'talk_id' => $talkId ) ); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } } \ No newline at end of file
farrelley/joind.in-api-client
298d773dfcdfb9e1c767f1d707ef05b7bf758369
added phpdocblock comments
diff --git a/library/FarleyHills/Service/JoindIn/Site.php b/library/FarleyHills/Service/JoindIn/Site.php index 998b2a7..2781945 100644 --- a/library/FarleyHills/Service/JoindIn/Site.php +++ b/library/FarleyHills/Service/JoindIn/Site.php @@ -1,36 +1,55 @@ <?php /** - * + * Site - get the current status of the web service * @author Shaun Farrell * */ class FarleyHills_Service_JoindIn_Site extends FarleyHills_Service_JoindIn { + /** + * api endpoint for site methods + * @var string + */ protected static $_endPoint = 'site'; + + /** + * supported site methods + * @var $_supportedMethods array + */ protected $_supportedMethods = array( 'status', ); + /** + * + * @param string $username + * @param string $password + * @param string $responseFormat + */ public function __construct($username = null, $password = null, $responseFormat = null) { $this->setResponseFormat($responseFormat); parent::__construct($username, $password); } + /** + * Get site's current status + * @param string $testString + * @return Zend_Http_Response + */ protected function _status($testString) { $methodType = 'status'; $action = array('type' => $methodType, 'data' => array('test_string' => $testString)); $this->_authenticationRequired = false; $this->_init(); $response = $this->_post(self::$_endPoint. '/' . $methodType, $action); if ('array' === $this->getResponseFormat()) { return Zend_Json::decode($response->getBody()); } return $response->getBody(); } - } \ No newline at end of file