CombinedText stringlengths 4 3.42M |
|---|
require "httparty"
require "net/http/capture" # BUGBUG: httparty/capture should work; bug in HttpCapture I think...
require "cucumber/rest/steps/caching"
require "cucumber/rest/status"
SERVER_URI = URI.parse(ENV["AUTH_SERVER"] || "http://localhost:9393/")
PROXY_URI = URI.parse(ENV["PROXY_SERVER"]) if ENV["PROXY_SERVER"]
Before do
$zuul = ZuulClient.new(SERVER_URI, PROXY_URI)
end
module KnowsAboutResponses
def last_response
HttpCapture::RESPONSES.last
end
def last_response_json
MultiJson.load(last_response.body)
end
end
World(KnowsAboutResponses)
Fixed issue where proxy had to be set
require "httparty"
require "net/http/capture" # BUGBUG: httparty/capture should work; bug in HttpCapture I think...
require "cucumber/rest/steps/caching"
require "cucumber/rest/status"
SERVER_URI = URI.parse(ENV["AUTH_SERVER"] || "http://localhost:9393/")
PROXY_URI = ENV["PROXY_SERVER"] ? URI.parse(ENV["PROXY_SERVER"]) : nil
Before do
$zuul = ZuulClient.new(SERVER_URI, PROXY_URI)
end
module KnowsAboutResponses
def last_response
HttpCapture::RESPONSES.last
end
def last_response_json
MultiJson.load(last_response.body)
end
end
World(KnowsAboutResponses) |
_lib = File.realpath(File.join(File.dirname(__FILE__), '../../lib'))
$:.unshift(_lib) unless $:.include?(_lib)
ENV['CHEF_BROWSER_SETTINGS'] = File.expand_path(File.join(File.dirname(__FILE__),
'../fixtures/settings.rb'))
ENV['CHEF_ZERO_PORT'] ||= '4001'
require 'chef-browser'
require 'capybara/cucumber'
require 'net/http'
# Raise exception if `html_str` is not valid HTML according to
# http://html5.validator.nu/
def validate_html(html_str)
resp = Net::HTTP.start('html5.validator.nu') do |http|
http.post '/?out=text', html_str, { 'Content-Type' => 'text/html; charset=utf-8' }
end
resp.value # raise error if not 2xx
unless resp.body =~ /^The document is valid HTML5/
lines = []
html_str.lines.each_with_index do |line, i|
lines << "#{i+1}\t#{line}"
end
$stderr.puts "Invalid HTML:\n\n#{lines.join}\n\n#{resp.body}"
raise "Invalid HTML"
end
end
if ENV['VALIDATE_HTML']
Capybara.app = lambda do |env|
resp = ChefBrowser::App.call(env)
resp[2] = [ resp[2].join ]
validate_html(resp[2].first) if resp[0] == 200 && resp[1]['Content-Type'] =~ /^text\/html\s*(;.*)?$/
resp
end
else
Capybara.app = ChefBrowser::App
end
require 'wrong'
World(Wrong)
Fix validators encoding issue.
_lib = File.realpath(File.join(File.dirname(__FILE__), '../../lib'))
$:.unshift(_lib) unless $:.include?(_lib)
ENV['CHEF_BROWSER_SETTINGS'] = File.expand_path(File.join(File.dirname(__FILE__),
'../fixtures/settings.rb'))
ENV['CHEF_ZERO_PORT'] ||= '4001'
require 'chef-browser'
require 'capybara/cucumber'
require 'net/http'
# Raise exception if `html_str` is not valid HTML according to
# http://html5.validator.nu/
def validate_html(html_str)
resp = Net::HTTP.start('html5.validator.nu') do |http|
http.post '/?out=text', html_str, { 'Content-Type' => 'text/html; charset=utf-8' }
end
resp.value # raise error if not 2xx
unless resp.body =~ /^The document is valid HTML5/
lines = []
html_str.lines.each_with_index do |line, i|
lines << "#{i+1}\t#{line}"
end
$stderr.puts "Invalid HTML:\n\n#{lines.join}\n\n#{resp.body.force_encoding('utf-8')}"
raise "Invalid HTML"
end
end
if ENV['VALIDATE_HTML']
Capybara.app = lambda do |env|
resp = ChefBrowser::App.call(env)
resp[2] = [ resp[2].join ]
validate_html(resp[2].first) if resp[0] == 200 && resp[1]['Content-Type'] =~ /^text\/html\s*(;.*)?$/
resp
end
else
Capybara.app = ChefBrowser::App
end
require 'wrong'
World(Wrong)
|
$LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib')
require 'database_cleaner'
require 'spec/expectations'
require 'test/unit/assertions'
World do |world|
world
end
removed extraneous world call from features
$LOAD_PATH.unshift(File.dirname(__FILE__) + '/../../lib')
require 'database_cleaner'
require 'spec/expectations'
require 'test/unit/assertions'
|
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# instead of editing this one. Cucumber will automatically load all features/**/*.rb
# files.
## This is custom functionality written by Refinery CMS.
def setup_environment
ENV["RAILS_ENV"] ||= "cucumber"
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
require 'cucumber/rails/world'
require 'cucumber/rails/active_record'
require 'cucumber/web/tableish'
require 'capybara/rails'
require 'capybara/cucumber'
require 'capybara/session'
require 'cucumber/rails/capybara_javascript_emulation' # Lets you click links with onclick javascript handlers without using @culerity or @javascript
# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In
# order to ease the transition to Capybara we set the default here. If you'd
# prefer to use XPath just remove this line and adjust any selectors in your
# steps to use the XPath syntax.
Capybara.default_selector = :css
end
def each_run
# If you set this to false, any error raised from within your app will bubble
# up to your step definition and out to cucumber unless you catch it somewhere
# on the way. You can make Rails rescue errors and render error pages on a
# per-scenario basis by tagging a scenario or feature with the @allow-rescue tag.
#
# If you set this to true, Rails will rescue all errors and render error
# pages, more or less in the same way your application would behave in the
# default production environment. It's not recommended to do this for all
# of your scenarios, as this makes it hard to discover errors in your application.
ActionController::Base.allow_rescue = false
# If you set this to true, each scenario will run in a database transaction.
# You can still turn off transactions on a per-scenario basis, simply tagging
# a feature or scenario with the @no-txn tag. If you are using Capybara,
# tagging with @culerity or @javascript will also turn transactions off.
#
# If you set this to false, transactions will be off for all scenarios,
# regardless of whether you use @no-txn or not.
#
# Beware that turning transactions off will leave data in your database
# after each scenario, which can lead to hard-to-debug failures in
# subsequent scenarios. If you do this, we recommend you create a Before
# block that will explicitly put your database in a known state.
Cucumber::Rails::World.use_transactional_fixtures = true
# How to clean your database when transactions are turned off. See
# http://github.com/bmabey/database_cleaner for more info.
if defined?(ActiveRecord::Base)
begin
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
rescue LoadError => ignore_if_database_cleaner_not_present
end
end
require 'authlogic/test_case'
Before do
activate_authlogic
end
end
if RUBY_PLATFORM !~ /mswin|mingw/
require 'spork'
Spork.prefork do
setup_environment
end
Spork.each_run do
each_run
end
else
setup_environment
each_run
end
Fixed mswin inclusion/exclusion criteria.
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# instead of editing this one. Cucumber will automatically load all features/**/*.rb
# files.
## This is custom functionality written by Refinery CMS.
def setup_environment
ENV["RAILS_ENV"] ||= "cucumber"
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
unless RUBY_PLATFORM !=~ /mswin|mingw/
require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
end
require 'cucumber/rails/world'
require 'cucumber/rails/active_record'
require 'cucumber/web/tableish'
require 'capybara/rails'
require 'capybara/cucumber'
require 'capybara/session'
require 'cucumber/rails/capybara_javascript_emulation' # Lets you click links with onclick javascript handlers without using @culerity or @javascript
# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In
# order to ease the transition to Capybara we set the default here. If you'd
# prefer to use XPath just remove this line and adjust any selectors in your
# steps to use the XPath syntax.
Capybara.default_selector = :css
end
def each_run
# If you set this to false, any error raised from within your app will bubble
# up to your step definition and out to cucumber unless you catch it somewhere
# on the way. You can make Rails rescue errors and render error pages on a
# per-scenario basis by tagging a scenario or feature with the @allow-rescue tag.
#
# If you set this to true, Rails will rescue all errors and render error
# pages, more or less in the same way your application would behave in the
# default production environment. It's not recommended to do this for all
# of your scenarios, as this makes it hard to discover errors in your application.
ActionController::Base.allow_rescue = false
# If you set this to true, each scenario will run in a database transaction.
# You can still turn off transactions on a per-scenario basis, simply tagging
# a feature or scenario with the @no-txn tag. If you are using Capybara,
# tagging with @culerity or @javascript will also turn transactions off.
#
# If you set this to false, transactions will be off for all scenarios,
# regardless of whether you use @no-txn or not.
#
# Beware that turning transactions off will leave data in your database
# after each scenario, which can lead to hard-to-debug failures in
# subsequent scenarios. If you do this, we recommend you create a Before
# block that will explicitly put your database in a known state.
Cucumber::Rails::World.use_transactional_fixtures = true
# How to clean your database when transactions are turned off. See
# http://github.com/bmabey/database_cleaner for more info.
if defined?(ActiveRecord::Base)
begin
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
rescue LoadError => ignore_if_database_cleaner_not_present
end
end
require 'authlogic/test_case'
Before do
activate_authlogic
end
end
if RUBY_PLATFORM !=~ /mswin|mingw/
require 'spork'
Spork.prefork do
setup_environment
end
Spork.each_run do
each_run
end
else
setup_environment
each_run
end
|
require 'aruba/cucumber'
require 'stack_master'
require 'stack_master/testing'
require 'aruba/in_process'
require 'pry'
require 'cucumber/rspec/doubles'
Aruba.configure do |config|
config.command_launcher = :in_process
config.main_class = StackMaster::CLI
end
Before do
StackMaster.cloud_formation_driver.reset
StackMaster.s3_driver.reset
StackMaster.reset_flags
end
lib = File.join(File.dirname(__FILE__), "../../spec/fixtures/sparkle_pack_integration/my_sparkle_pack/lib")
$LOAD_PATH << lib
Fix build failures from deprecated require
require 'aruba/cucumber'
require 'stack_master'
require 'stack_master/testing'
require 'aruba/processes/in_process'
require 'pry'
require 'cucumber/rspec/doubles'
Aruba.configure do |config|
config.command_launcher = :in_process
config.main_class = StackMaster::CLI
end
Before do
StackMaster.cloud_formation_driver.reset
StackMaster.s3_driver.reset
StackMaster.reset_flags
end
lib = File.join(File.dirname(__FILE__), "../../spec/fixtures/sparkle_pack_integration/my_sparkle_pack/lib")
$LOAD_PATH << lib
|
require 'aruba/cucumber'
Fix require problem with cucumber
require 'aruba/cucumber'
Before do
set_env('RUBYOPT', "-I ../../lib")
end
|
ENV['RACK_ENV'] = 'test'
# NOTE: This must come before the require 'webrat', otherwise
# sinatra will look in the wrong place for its views.
require File.dirname(__FILE__) + '/../../eee'
# Force the application name because polyglot breaks the auto-detection logic.
Sinatra::Application.app_file = File.join(File.dirname(__FILE__), *%w[.. .. eee.rb])
# RSpec matchers
require 'spec/expectations'
# Webrat
require 'webrat'
Webrat.configure do |config|
config.mode = :sinatra
end
World do
session = Webrat::SinatraSession.new
session.extend(Webrat::Matchers)
session.extend(Webrat::HaveTagMatcher)
session
end
Before do
RestClient.put @@db, { }
# TODO need to accomplish this via CouchDB migrations
lucene_index_function = <<_JS
function(doc) {
var ret = new Document();
function idx(obj) {
for (var key in obj) {
switch (typeof obj[key]) {
case 'object':
/* Handle ingredients as a special case */
if (key == 'preparations') {
var ingredients = [];
for (var i=0; i<obj[key].length; i++) {
ingredients.push(obj[key][i]['ingredient']['name']);
}
ret.field('ingredient', ingredients.join(', '), 'yes');
ret.field('all', ingredients.join(', '));
}
else {
idx(obj[key]);
}
break;
case 'function':
break;
default:
ret.field(key, obj[key]);
ret.field('all', obj[key]);
break;
}
}
}
idx(doc);
ret.field('sort_title', doc['title'], 'yes', 'not_analyzed');
ret.field('sort_date', doc['date'], 'yes', 'not_analyzed');
ret.field('sort_prep', doc['prep_time'], 'yes', 'not_analyzed');
var ingredient_count = doc['preparations'] ? doc['preparations'].length : 0;
ret.field('sort_ingredient', ingredient_count, 'yes', 'not_analyzed');
ret.field('date', doc['date'], 'yes');
ret.field('title', doc['title'], 'yes');
ret.field('prep_time', doc['prep_time'], 'yes');
return ret;
}
_JS
doc = { 'transform' => lucene_index_function }
RestClient.put "#{@@db}/_design/lucene",
doc.to_json,
:content_type => 'application/json'
end
After do
RestClient.delete @@db
sleep 0.5
end
To eliminate intermittent failures, update the sort by prep / number of ingredients to be strings.
ENV['RACK_ENV'] = 'test'
# NOTE: This must come before the require 'webrat', otherwise
# sinatra will look in the wrong place for its views.
require File.dirname(__FILE__) + '/../../eee'
# Force the application name because polyglot breaks the auto-detection logic.
Sinatra::Application.app_file = File.join(File.dirname(__FILE__), *%w[.. .. eee.rb])
# RSpec matchers
require 'spec/expectations'
# Webrat
require 'webrat'
Webrat.configure do |config|
config.mode = :sinatra
end
World do
session = Webrat::SinatraSession.new
session.extend(Webrat::Matchers)
session.extend(Webrat::HaveTagMatcher)
session
end
Before do
RestClient.put @@db, { }
# TODO need to accomplish this via CouchDB migrations
lucene_index_function = <<_JS
function(doc) {
var ret = new Document();
function zero_pad(i, number_of_zeroes) {
var ret = i + "";
while (ret.length < number_of_zeroes) {
ret = "0" + ret;
}
return ret;
}
function idx(obj) {
for (var key in obj) {
switch (typeof obj[key]) {
case 'object':
/* Handle ingredients as a special case */
if (key == 'preparations') {
var ingredients = [];
for (var i=0; i<obj[key].length; i++) {
ingredients.push(obj[key][i]['ingredient']['name']);
}
ret.field('ingredient', ingredients.join(', '), 'yes');
ret.field('all', ingredients.join(', '));
}
else {
idx(obj[key]);
}
break;
case 'function':
break;
default:
ret.field(key, obj[key]);
ret.field('all', obj[key]);
break;
}
}
}
idx(doc);
ret.field('sort_title', doc['title'], 'yes', 'not_analyzed');
ret.field('sort_date', doc['date'], 'yes', 'not_analyzed');
ret.field('sort_prep', zero_pad(doc['prep_time'], 5), 'yes', 'not_analyzed');
var ingredient_count = doc['preparations'] ? doc['preparations'].length : 0;
ret.field('sort_ingredient', zero_pad(ingredient_count, 5), 'yes', 'not_analyzed');
ret.field('date', doc['date'], 'yes');
ret.field('title', doc['title'], 'yes');
ret.field('prep_time', doc['prep_time'], 'yes');
return ret;
}
_JS
doc = { 'transform' => lucene_index_function }
RestClient.put "#{@@db}/_design/lucene",
doc.to_json,
:content_type => 'application/json'
end
After do
RestClient.delete @@db
sleep 0.5
end
|
# Encoding: utf-8
require File.dirname(__FILE__) + '/../spec_helper'
module Qubell
describe Configuration do
describe '#endpoint' do
it 'default value is https://express.qubell.com' do
expect(Qubell::Configuration.new.endpoint).to eq('https://express.qubell.com')
end
it 'can set value' do
config = Qubell::Configuration.new
config.endpoint = 'test'
expect(config.endpoint).to eq('test')
end
end
describe '#api_version' do
it 'default value is 1' do
expect(Qubell::Configuration.new.api_version).to eq('1')
end
it 'can set value' do
config = Qubell::Configuration.new
config.api_version = '2'
expect(config.api_version).to eq('2')
end
end
describe '#username' do
it 'default value is nil' do
expect(Qubell::Configuration.new.username).to eq(nil)
end
it 'can set value' do
config = Qubell::Configuration.new
config.username = 'username'
expect(config.username).to eq('username')
end
end
describe '#password' do
it 'default value is nil' do
expect(Qubell::Configuration.new.password).to eq(nil)
end
it 'can set value' do
config = Qubell::Configuration.new
config.password = 'password'
expect(config.password).to eq('password')
end
end
describe '#to_s' do
it 'return json string' do
config = Qubell::Configuration.new
config.username = 'username'
config.password = 'password'
expect(config.to_s).to eq('{"endpoint": "https://express.qubell.com",' \
'"api_version": "1",' \
'"username": "username",' \
'"password": "password"}')
end
end
end
end
#
# describe QubellAPI do
# describe 'constractor' do
# describe 'without required parameters' do
# it 'requires username' do
# expect { QubellAPI.new }.to raise_error(KeyError)
# expect { QubellAPI.new(password: 'password') }.to raise_error(KeyError)
# end
#
# it 'requires password' do
# expect { QubellAPI.new(username: 'test') }.to raise_error(KeyError)
# end
# end
#
# describe 'with required parameters' do
# let(:resource) { QubellAPI.new(username: 'test', password: 'password') }
#
# it 'has default endpoint' do
# expect(resource.endpoint).to eql('https://express.qubell.com')
# end
#
# it 'has default api version' do
# expect(resource.api_version).to eql('1')
# end
# end
#
# describe 'with additional parameters' do
# let(:resource) do
# QubellAPI.new(
# username: 'test',
# password: 'password',
# endpoint: 'http://test.qubell.com',
# api_version: '2')
# end
# let(:endpoint) { resource.endpoint }
# let(:api_version) { resource.api_version }
#
# it 'uses specified endpoint' do
# expect(resource.endpoint).to equal(endpoint)
# end
#
# it 'uses specified api version' do
# expect(resource.api_version).to equal(api_version)
# end
# end
# end
#
# describe 'public methods' do
# let(:resource) { QubellAPI.new(username: 'test', password: 'password') }
# let(:endpoint) { resource.endpoint }
# let(:api_version) { resource.api_version }
# let(:base_url) { "#{endpoint.sub!(%r{\/\/}, '//user:pass@')}" }
# let(:app_id) { '50dd88bee4b082b7a96d072e' }
# let(:org_id) { '50dd88bee4b082b7a96d072e' }
# let(:env_id) { '50dd88bee4b082b7a96d072e' }
#
# describe 'get_organizations' do
# let(:url) do
# "#{base_url}/api/#{api_version}/organizations"
# end
# let(:data) { '[{"id": "50dd88bee4b082b7a96d072e", "name": "TestOrg"}]' }
#
# subject { resource.organizations }
#
# it_behaves_like 'common_get_method'
# end
#
# describe 'get_applications(org_id)' do
# let(:url) do
# "#{base_url}/api/#{api_version}/organizations/#{org_id}/applications"
# end
# let(:data) { '[{"id": "50dd88bee4b082b7a96d072e", "name": "TestApp"}]' }
#
# subject { resource.applications(org_id) }
#
# context 'with valid organization id' do
# it_behaves_like 'common_get_method'
# end
#
# context 'with invalid organization id' do
# it_behaves_like 'unexisting resource response'
# end
# end
#
# describe 'get_revisions(app_id)' do
# let(:url) do
# "#{base_url}/api/#{api_version}/applications/#{app_id}/revisions"
# end
# let(:data) { '[{"id": "50dd88bee4b082b7a96d072e", "name": "TestRev"}]' }
#
# subject { resource.revisions(app_id) }
#
# it_behaves_like 'common_get_method'
#
# context 'with invalid revision id' do
# it_behaves_like 'unexisting resource response'
# end
# end
#
# describe 'get_instances(env_id)' do
# let(:url) do
# "#{base_url}/api/#{api_version}/environments/#{env_id}/instances"
# end
# let(:data) { '[{"id": "50dd88bee4b082b7a96d072e", "name": "TestRev"}]' }
#
# subject { resource.instances(env_id) }
#
# # if 'sadasd' do
# # File.stub(:open).with("manifest","yaml") { StringIO.new(data) }
# # end
# context 'with invalid revision id' do
# it_behaves_like 'unexisting resource response'
# end
# end
# end
# end
Remove legacy tests
# Encoding: utf-8
require File.dirname(__FILE__) + '/../spec_helper'
module Qubell
describe Configuration do
describe '#endpoint' do
it 'default value is https://express.qubell.com' do
expect(Qubell::Configuration.new.endpoint).to eq('https://express.qubell.com')
end
it 'can set value' do
config = Qubell::Configuration.new
config.endpoint = 'test'
expect(config.endpoint).to eq('test')
end
end
describe '#api_version' do
it 'default value is 1' do
expect(Qubell::Configuration.new.api_version).to eq('1')
end
it 'can set value' do
config = Qubell::Configuration.new
config.api_version = '2'
expect(config.api_version).to eq('2')
end
end
describe '#username' do
it 'default value is nil' do
expect(Qubell::Configuration.new.username).to eq(nil)
end
it 'can set value' do
config = Qubell::Configuration.new
config.username = 'username'
expect(config.username).to eq('username')
end
end
describe '#password' do
it 'default value is nil' do
expect(Qubell::Configuration.new.password).to eq(nil)
end
it 'can set value' do
config = Qubell::Configuration.new
config.password = 'password'
expect(config.password).to eq('password')
end
end
describe '#to_s' do
it 'return json string' do
config = Qubell::Configuration.new
config.username = 'username'
config.password = 'password'
expect(config.to_s).to eq('{"endpoint": "https://express.qubell.com",' \
'"api_version": "1",' \
'"username": "username",' \
'"password": "password"}')
end
end
end
end
|
Todo : Tests for Conditionnal_tree_building
require 'test/unit'
require 'fpgrowth/miner/conditional_tree_builder'
class TestConditonalTreeBuilder < Test::Unit::TestCase
# Called before every test method runs. Can be used
# to set up fixture information.
def setup
# Do nothing
end
# Called after every test method runs. Can be used to tear
# down fixture information.
def teardown
# Do nothing
end
# Fake test
def test_fail
# To change this template use File | Settings | File Templates.
fail('Not implemented')
end
end |
require_relative 'test_case'
require 'tunit/assertion_errors'
require 'tunit/test'
module Tunit
class AssertionErrorTest < TestCase
def setup
self.assertion = Assertion.new
end
attr_accessor :assertion
def test_error
assert_instance_of Assertion, assertion.error
end
def test_location
result = FailingTest.new.run
assertion = result.failure
exp_location = %r(.*/tunit/test/tunit/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "F", assertion.result_code
end
def test_result_label
assert_equal "Failure", assertion.result_label
end
end
class EmptyErrorTest < TestCase
def setup
self.assertion = Empty.new
end
attr_accessor :assertion
def test_error
assert_instance_of Empty, assertion.error
end
def test_location
result = FailingTest.new(:test_empty).run
assertion = result.failure
exp_location = %r(.*/tunit/test/tunit/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_location_handles_unnamed_classes
result = Class.new(Test) {
def test_empty
end
}.new(:test_empty).run
refute_equal :not_set, result.failure.location
end
def test_result_code
assert_equal "_", assertion.result_code
end
def test_result_label
assert_equal "Empty", assertion.result_label
end
end
class SkipErrorTest < TestCase
def setup
self.assertion = Skip.new
end
attr_accessor :assertion
def test_error
assert_instance_of Skip, assertion.error
end
def test_location
result = SkippedTest.new.run
assertion = result.failure
exp_location = %r(.*/tunit/test/tunit/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "S", assertion.result_code
end
def test_result_label
assert_equal "Skipped", assertion.result_label
end
end
end
Improve assertion
If the repository name is different than indented, it will fail
Also do a valid assertion for un-named classes testcase
require_relative 'test_case'
require 'tunit/assertion_errors'
require 'tunit/test'
module Tunit
class AssertionErrorTest < TestCase
def setup
self.assertion = Assertion.new
end
attr_accessor :assertion
def test_error
assert_instance_of Assertion, assertion.error
end
def test_location
result = FailingTest.new.run
assertion = result.failure
exp_location = %r(test/tunit/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "F", assertion.result_code
end
def test_result_label
assert_equal "Failure", assertion.result_label
end
end
class EmptyErrorTest < TestCase
def setup
self.assertion = Empty.new
end
attr_accessor :assertion
def test_error
assert_instance_of Empty, assertion.error
end
def test_location
result = FailingTest.new(:test_empty).run
assertion = result.failure
exp_location = %r(/test/tunit/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_location_handles_unnamed_classes
result = Class.new(Test) {
def test_empty
end
}.new(:test_empty).run
assertion = result.failure
exp_location = %r(/test/tunit/assertion_errors_test.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "_", assertion.result_code
end
def test_result_label
assert_equal "Empty", assertion.result_label
end
end
class SkipErrorTest < TestCase
def setup
self.assertion = Skip.new
end
attr_accessor :assertion
def test_error
assert_instance_of Skip, assertion.error
end
def test_location
result = SkippedTest.new.run
assertion = result.failure
exp_location = %r(test/tunit/test_case.rb:\d{1,})
assert_match exp_location, assertion.location
end
def test_result_code
assert_equal "S", assertion.result_code
end
def test_result_label
assert_equal "Skipped", assertion.result_label
end
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{dm-data_objects-adapter}
s.version = "0.10.3"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Dan Kubb"]
s.date = %q{2010-02-02}
s.description = %q{DataObjects adapter for DataMapper}
s.email = %q{dan.kubb@gmail.com}
s.extra_rdoc_files = [
"LICENSE"
]
s.files = [
"LICENSE",
"VERSION",
"tasks/yard.rake",
"tasks/yardstick.rake"
]
s.homepage = %q{http://github.com/datamapper/dm-more/tree/master/adapters/dm-data_objects-adapter}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{datamapper}
s.rubygems_version = %q{1.3.5}
s.summary = %q{DataObjects adapter for DataMapper}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<data_objects>, ["~> 0.10.1"])
s.add_runtime_dependency(%q<dm-core>, ["~> 0.10.3"])
s.add_development_dependency(%q<yard>, ["~> 0.5"])
else
s.add_dependency(%q<data_objects>, ["~> 0.10.1"])
s.add_dependency(%q<dm-core>, ["~> 0.10.3"])
s.add_dependency(%q<yard>, ["~> 0.5"])
end
else
s.add_dependency(%q<data_objects>, ["~> 0.10.1"])
s.add_dependency(%q<dm-core>, ["~> 0.10.3"])
s.add_dependency(%q<yard>, ["~> 0.5"])
end
end
Added mising dep for dm-data_objects-adapter and regenerated gemspecs
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{dm-data_objects-adapter}
s.version = "0.10.3"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Dan Kubb"]
s.date = %q{2010-02-04}
s.description = %q{DataObjects adapter for DataMapper}
s.email = %q{dan.kubb@gmail.com}
s.extra_rdoc_files = [
"LICENSE"
]
s.files = [
"LICENSE",
"Rakefile",
"VERSION",
"dm-data_objects-adapter.gemspec",
"lib/data_objects_adapter.rb",
"lib/data_objects_adapter/spec/data_objects_adapter_shared_spec.rb",
"tasks/yard.rake",
"tasks/yardstick.rake"
]
s.homepage = %q{http://github.com/datamapper/dm-more/tree/master/adapters/dm-data_objects-adapter}
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{datamapper}
s.rubygems_version = %q{1.3.5}
s.summary = %q{DataObjects adapter for DataMapper}
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<data_objects>, ["~> 0.10.1"])
s.add_runtime_dependency(%q<dm-core>, ["~> 0.10.3"])
s.add_development_dependency(%q<yard>, ["~> 0.5"])
else
s.add_dependency(%q<data_objects>, ["~> 0.10.1"])
s.add_dependency(%q<dm-core>, ["~> 0.10.3"])
s.add_dependency(%q<yard>, ["~> 0.5"])
end
else
s.add_dependency(%q<data_objects>, ["~> 0.10.1"])
s.add_dependency(%q<dm-core>, ["~> 0.10.3"])
s.add_dependency(%q<yard>, ["~> 0.5"])
end
end
|
class CartController < ApplicationController
include CartHelper
include PaypalExpressHelper
include ActionView::Helpers::NumberHelper
force_ssl if Rails.env.production?
layout 'single_column'
def load_or_create_order
key = cookies[:cart]
# create new order if necessary
if key.blank?
key = SecureRandom.hex
cookies[:cart] = key
end
# load existing order from database
order = Order.includes(:items, [items: [:product, :affiliate]]).find_by(cart_key: key)
if order.nil?
order = Order.new(cart_key: key,
status: 'in cart',
payment_method: 'CREDIT_CARD',
domain_id: Rails.configuration.domain_id,
sales_channel: Cache.setting(Rails.configuration.domain_id, :system, "Website Name"))
order.save validate: false
end
order
end
# GET /cart
def index
key = cookies[:cart]
@order = Order.includes(:items, [items: [:product, :affiliate]]).find_by(cart_key: key) unless key.nil?
end
# GET /cart/add
def add
order = load_or_create_order
# iterate through multiple items being added to cart
# key = {product-id}-{affiliate-id}-{variation}
params.each do |key, val|
next unless key.include?('qty-')
key = key.split('-')
affiliate_id = nil
variation = nil
product_id = key[1].to_i
affiliate_id = key[2].to_i unless key.length < 3
variation = key[3] unless key.length < 4
quantity = val.to_i
next unless quantity > 0
p = Product.find(product_id)
#check if item already exists
item = order.items.find do |i|
i.product_id == product_id &&
i.affiliate_id == affiliate_id &&
i.variation == variation &&
i.custom_text == params[:custom_text] &&
i.uploaded_file == params[:uploaded_file] &&
i.start_x_percent == params[:start_x_percent] &&
i.start_y_percent == params[:start_y_percent] &&
i.width_percent == params[:width_percent] &&
i.height_percent == params[:height_percent]
end
if item.nil?
item = OrderItem.new order_id: order.id,
product_id: product_id,
affiliate_id: affiliate_id,
variation: variation,
quantity: quantity,
unit_price: p.special_price || p.price,
item_description: p.name_with_option,
uploaded_file: params[:uploaded_file],
start_x_percent: params[:start_x_percent],
start_y_percent: params[:start_y_percent],
width_percent: params[:width_percent],
height_percent: params[:height_percent],
custom_text: params[:custom_text],
autoship_months: params[:autoship_months].blank? ? 0 : params[:autoship_months]
item.item_number = p.sku
item.item_number += "-" + Affiliate.find(affiliate_id).code unless affiliate_id.nil?
item.item_number += "-" + variation unless variation.nil?
order.items << item
# create image preview if this is a personalized product
ImagePreviewJob.new(item.id).perform_later unless item.uploaded_file.nil?
else
item.quantity += quantity
item.autoship_months = params[:autoship_months].blank? ? 0 : item.autoship_months
item.save
end
end
update_totals order
order.save validate: false
respond_to do |format|
format.html do
if params[:redirect].nil?
redirect_to action: 'index'
else
redirect_to params[:redirect]
end
end
format.js { render layout: false }
end
end
# GET /cart/add_deal
def add_deal
dd = DailyDeal.find(params[:daily_deal_id])
unless dd.active && dd.start_time < DateTime.now && dd.end_time > DateTime.now
flash[:error] = "This deal is not currently active."
return redirect_to action: 'index'
end
if dd.number_sold >= dd.max_sales
flash[:error] = "Sorry, this deal is sold out."
return redirect_to action: 'index'
end
order = load_or_create_order
# add item to cart
item = order.items.find { |i| i.daily_deal_id == dd.id && i.custom_text == params[:order_specifications] }
if item.nil?
item = OrderItem.new order_id: order.id,
daily_deal_id: dd.id,
quantity: params[:qty],
unit_price: dd.deal_price,
item_description: dd.short_tag_line,
item_number: "DEAL#{dd.id}",
custom_text: params[:order_specifications]
order.items << item
else
item.quantity += params[:qty].to_i
item.save
end
if dd.max_per_user && (item.quantity > dd.max_per_user)
flash[:error] = "Sorry, this deal is limited to #{dd.max_per_user} per customer."
item.update_attribute(:quantity, dd.max_per_user)
end
update_totals order
order.save(validate: false)
respond_to do |format|
format.html { redirect_to action: 'index' }
format.js { render layout: false }
end
end
# GET /cart/apply_fb_discount?dd=
def apply_fb_discount
dd = DailyDeal.find(params[:dd])
order = load_or_create_order
order.fb_discount = dd.fb_discount
order.save(validate: false)
render json: { status: :ok }
end
def remove
id = params[:id].to_i
order = Order.includes(:items).find_by(cart_key: cookies[:cart]) unless cookies[:cart].nil?
if order != nil
item = order.items.find { |t| t.id == id }
unless item.nil?
order.items.destroy(item)
# update order or delete altogether if no items left
if order.items.length > 0
update_totals order
order.save validate: false
else
order.destroy
end
end
end
redirect_to :back
end
def update
order = Order.includes(:items).find_by(cart_key: cookies[:cart]) unless cookies[:cart].nil?
return redirect_to :back if order.nil?
# iterate through items
params.each do |key, val|
next unless key.include?('qty-')
item_id = key[4..-1].to_i
quantity = val.to_i
item = order.items.find { |item| item.id == item_id }
next if item.nil?
if quantity > 0
item.quantity = quantity
# special check for daily deals
if item.daily_deal && item.daily_deal.max_per_user && (item.quantity > item.daily_deal.max_per_user)
flash[:error] = "Sorry, #{item.item_number} is limited to #{item.daily_deal.max_per_user} per customer."
item.quantity = item.daily_deal.max_per_user
end
item.save
else
order.items.destroy(item)
end
end
# update order or delete altogether if no items left
if order.items.length > 0
update_totals order
order.save validate: false
else
order.destroy
end
flash[:notice] = 'Your shopping cart has been updated.'
redirect_to :back
end
# GET /cart/personalize?item=ITEM_NUMBER
def personalize
@order = load_or_create_order
@product = Product.find_by(item_number: params[:item])
end
# POST /cart/upload_picture
def upload_picture
file_path = Cache.setting(Rails.configuration.domain_id, "System", "Static Files Path")
uploaded_io = params[:file]
ext = uploaded_io.original_filename.split('.').last.downcase
unless uploaded_io.nil? || ['jpg', 'jpeg', 'tiff', 'gif', 'bmp'].include?(ext) == false
file_name = SecureRandom.hex(6) + '.' + ext
file_path = file_path + '/uploads/' + file_name
File.open(file_path, 'wb') do |file|
file.write(uploaded_io.read)
end
order = load_or_create_order
order.pictures.create(file_path: '/uploads/' + file_name, user_id: session[:user_id], caption: 'user upload')
return render json: { status: 'ok', file_path: '/uploads/' + file_name }
end
render json: { status: 'error', message: "Not a valid image file" }
end
def checkout
@order = Order.includes(:items).find_by(cart_key: cookies[:cart]) unless cookies[:cart].nil?
return redirect_to action: 'index' if (@order.nil? || @order.items.length == 0)
# check if login is required
if (session[:user_id].nil? && Cache.setting(Rails.configuration.domain_id, "eCommerce", "Checkout Require Login") == "true")
flash[:notice] = "Please log in to proceed with checkout"
return redirect_to "/login?redirect=/cart/checkout"
end
# retrieve info from previous order if user is logged in
if @order.user_id.nil? && !session[:user_id].nil?
@order.user_id = session[:user_id]
previous_order = Order.order('submitted DESC').find_by(user_id: @order.user_id, status: ['submitted', 'completed', 'shipped'])
unless previous_order.nil?
@order.shipping_name = previous_order.shipping_name
@order.shipping_street1 = previous_order.shipping_street1
@order.shipping_street2 = previous_order.shipping_street2
@order.shipping_city = previous_order.shipping_city
@order.shipping_state = previous_order.shipping_state
@order.shipping_zip = previous_order.shipping_zip
@order.shipping_country = previous_order.shipping_country
@order.notify_email = previous_order.notify_email
@order.contact_phone = previous_order.contact_phone
else
user = User.find(session[:user_id])
@order.notify_email = user.email
@order.contact_phone = user.phone
end
end
# set payment_method depending on total. PAYPAL would never reach this point
@order.payment_method = @order.total > 0.0 ? "CREDIT_CARD" : "NO_BILLING"
end
def checkout_update
@order = Order.includes(:items).find_by(cart_key: cookies[:cart]) unless cookies[:cart].nil?
return redirect_to action: 'index' if @order.nil? || @order.items.length == 0
@order.assign_attributes(order_params)
# update billing name otherwise credit card validation will fail
if @order.paid_with_card? && @order.same_as_shipping == '1'
@order.billing_name = @order.shipping_name
@order.billing_street1 = @order.shipping_street1
@order.billing_street2 = @order.shipping_street2
@order.billing_city = @order.shipping_city
@order.billing_state = @order.shipping_state
@order.billing_zip = @order.shipping_zip
@order.billing_country = @order.shipping_country
end
if @order.valid?
update_totals(@order)
@order.save(validate: false)
return redirect_to action: 'review'
end
render 'checkout'
end
def review
@order = Order.includes(:items).find_by(cart_key: cookies[:cart])
redirect_to action: 'index' if @order.nil? || @order.items.length == 0
end
def submit
@order = Order.includes(:items).find(params[:id])
@order.user_id = session[:user_id] if @order.user_id.nil? # attach order to logged-in user
@order.create_user if @order.user_id.nil?
# Double check if voucher is not being reused. this can happen if user has multiple
# carts in different browsers, all not check-out yet, but voucher applied, i.e. the
# voucher hasn't been marked as claimed yet.
unless @order.voucher_id.nil?
voucher = Voucher.find(@order.voucher_id)
if voucher.amount_used + @order.credit_applied > voucher.voucher_group.value
@order.errors.add :base, "Voucher has already been used. Please review changed to your order."
@order.voucher_id = nil
update_totals @order
@order.save
return render 'review'
end
end
# PROCESS PAYMENT
begin
@order.process_payment(request)
rescue => e
@order.errors.add :base, e.message
return render "review"
end
# IMPORTANT: save the order!
@order.save validate: false
# Do other stuff like deal counter updates, affiliate commission etc.
WebOrderJob.perform_later(order_id: @order.id,
email_blast_uuid: cookies[:ebuuid],
referral_key: cookies[:refkey],
affiliate_campaign_id: cookies[:acid])
# delete cart cookie and display confirmation
cookies.delete :cart
session[:order_id] = @order.id
redirect_to action: 'submitted', id: @order.id
end
def submitted
@order = Order.includes(:items).find(session[:order_id])
end
def applycode
# load order
applied = false
order = Order.includes(:items).find_by(cart_key: cookies[:cart])
# test if code is a coupon code
coupon = Coupon.find_by(code: params[:code])
unless coupon.nil?
applied = true
if (coupon.times_used > coupon.max_uses)
flash[:notice] = 'This coupon is no longer available.'
elsif coupon.start_time > Time.now || coupon.expire_time < Time.now
flash[:notice] = 'This coupon has expired.'
elsif coupon.min_order_amount && order.subtotal < coupon.min_order_amount
flash[:notice] = "This coupon is only valid for orders over #{number_to_currency(coupon.min_order_amount)}."
else
order.coupon_id = coupon.id
update_totals order
order.save validate: false
flash[:notice] = "Coupon code '#{coupon.code}' has been applied to your order."
end
# test if code is a voucher code
else
voucher = Voucher.find_by(code: params[:code])
unless voucher.nil?
if voucher.amount_used >= voucher.voucher_group.value
flash[:notice] = 'This voucher has already been claimed.'
elsif voucher.voucher_group.expires < Time.now
flash[:notice] = 'This voucher has expired.'
else
order.voucher_id = voucher.id
amt = voucher.voucher_group.value
update_totals order
order.save validate: false
applied = true
flash[:notice] = "A credit of $#{amt} has been applied to your order."
end
end
end
flash[:notice] = "Coupon or voucher code not found." unless applied
redirect_to :back
end
private
def order_params
params.require(:order).permit(:shipping_name, :shipping_street1, :shipping_street2, :shipping_city, :shipping_state,
:shipping_zip, :shipping_country, :contact_phone, :billing_name, :billing_street1, :billing_street2, :billing_city,
:billing_state, :billing_zip, :billing_country, :cc_type, :cc_number, :cc_expiration_month, :cc_expiration_year,
:cc_code, :notify_email, :customer_note, :payment_method, :same_as_shipping, :user_id)
end
end
image preview
class CartController < ApplicationController
include CartHelper
include PaypalExpressHelper
include ActionView::Helpers::NumberHelper
force_ssl if Rails.env.production?
layout 'single_column'
def load_or_create_order
key = cookies[:cart]
# create new order if necessary
if key.blank?
key = SecureRandom.hex
cookies[:cart] = key
end
# load existing order from database
order = Order.includes(:items, [items: [:product, :affiliate]]).find_by(cart_key: key)
if order.nil?
order = Order.new(cart_key: key,
status: 'in cart',
payment_method: 'CREDIT_CARD',
domain_id: Rails.configuration.domain_id,
sales_channel: Cache.setting(Rails.configuration.domain_id, :system, "Website Name"))
order.save validate: false
end
order
end
# GET /cart
def index
key = cookies[:cart]
@order = Order.includes(:items, [items: [:product, :affiliate]]).find_by(cart_key: key) unless key.nil?
end
# GET /cart/add
def add
order = load_or_create_order
# iterate through multiple items being added to cart
# key = {product-id}-{affiliate-id}-{variation}
params.each do |key, val|
next unless key.include?('qty-')
key = key.split('-')
affiliate_id = nil
variation = nil
product_id = key[1].to_i
affiliate_id = key[2].to_i unless key.length < 3
variation = key[3] unless key.length < 4
quantity = val.to_i
next unless quantity > 0
p = Product.find(product_id)
#check if item already exists
item = order.items.find do |i|
i.product_id == product_id &&
i.affiliate_id == affiliate_id &&
i.variation == variation &&
i.custom_text == params[:custom_text] &&
i.uploaded_file == params[:uploaded_file] &&
i.start_x_percent == params[:start_x_percent] &&
i.start_y_percent == params[:start_y_percent] &&
i.width_percent == params[:width_percent] &&
i.height_percent == params[:height_percent]
end
if item.nil?
item = OrderItem.new order_id: order.id,
product_id: product_id,
affiliate_id: affiliate_id,
variation: variation,
quantity: quantity,
unit_price: p.special_price || p.price,
item_description: p.name_with_option,
uploaded_file: params[:uploaded_file],
start_x_percent: params[:start_x_percent],
start_y_percent: params[:start_y_percent],
width_percent: params[:width_percent],
height_percent: params[:height_percent],
custom_text: params[:custom_text],
autoship_months: params[:autoship_months].blank? ? 0 : params[:autoship_months]
item.item_number = p.sku
item.item_number += "-" + Affiliate.find(affiliate_id).code unless affiliate_id.nil?
item.item_number += "-" + variation unless variation.nil?
order.items << item
# create image preview if this is a personalized product
ImagePreviewJob.perform_later(item.id) unless item.uploaded_file.nil?
else
item.quantity += quantity
item.autoship_months = params[:autoship_months].blank? ? 0 : item.autoship_months
item.save
end
end
update_totals order
order.save validate: false
respond_to do |format|
format.html do
if params[:redirect].nil?
redirect_to action: 'index'
else
redirect_to params[:redirect]
end
end
format.js { render layout: false }
end
end
# GET /cart/add_deal
def add_deal
dd = DailyDeal.find(params[:daily_deal_id])
unless dd.active && dd.start_time < DateTime.now && dd.end_time > DateTime.now
flash[:error] = "This deal is not currently active."
return redirect_to action: 'index'
end
if dd.number_sold >= dd.max_sales
flash[:error] = "Sorry, this deal is sold out."
return redirect_to action: 'index'
end
order = load_or_create_order
# add item to cart
item = order.items.find { |i| i.daily_deal_id == dd.id && i.custom_text == params[:order_specifications] }
if item.nil?
item = OrderItem.new order_id: order.id,
daily_deal_id: dd.id,
quantity: params[:qty],
unit_price: dd.deal_price,
item_description: dd.short_tag_line,
item_number: "DEAL#{dd.id}",
custom_text: params[:order_specifications]
order.items << item
else
item.quantity += params[:qty].to_i
item.save
end
if dd.max_per_user && (item.quantity > dd.max_per_user)
flash[:error] = "Sorry, this deal is limited to #{dd.max_per_user} per customer."
item.update_attribute(:quantity, dd.max_per_user)
end
update_totals order
order.save(validate: false)
respond_to do |format|
format.html { redirect_to action: 'index' }
format.js { render layout: false }
end
end
# GET /cart/apply_fb_discount?dd=
def apply_fb_discount
dd = DailyDeal.find(params[:dd])
order = load_or_create_order
order.fb_discount = dd.fb_discount
order.save(validate: false)
render json: { status: :ok }
end
def remove
id = params[:id].to_i
order = Order.includes(:items).find_by(cart_key: cookies[:cart]) unless cookies[:cart].nil?
if order != nil
item = order.items.find { |t| t.id == id }
unless item.nil?
order.items.destroy(item)
# update order or delete altogether if no items left
if order.items.length > 0
update_totals order
order.save validate: false
else
order.destroy
end
end
end
redirect_to :back
end
def update
order = Order.includes(:items).find_by(cart_key: cookies[:cart]) unless cookies[:cart].nil?
return redirect_to :back if order.nil?
# iterate through items
params.each do |key, val|
next unless key.include?('qty-')
item_id = key[4..-1].to_i
quantity = val.to_i
item = order.items.find { |item| item.id == item_id }
next if item.nil?
if quantity > 0
item.quantity = quantity
# special check for daily deals
if item.daily_deal && item.daily_deal.max_per_user && (item.quantity > item.daily_deal.max_per_user)
flash[:error] = "Sorry, #{item.item_number} is limited to #{item.daily_deal.max_per_user} per customer."
item.quantity = item.daily_deal.max_per_user
end
item.save
else
order.items.destroy(item)
end
end
# update order or delete altogether if no items left
if order.items.length > 0
update_totals order
order.save validate: false
else
order.destroy
end
flash[:notice] = 'Your shopping cart has been updated.'
redirect_to :back
end
# GET /cart/personalize?item=ITEM_NUMBER
def personalize
@order = load_or_create_order
@product = Product.find_by(item_number: params[:item])
end
# POST /cart/upload_picture
def upload_picture
file_path = Cache.setting(Rails.configuration.domain_id, "System", "Static Files Path")
uploaded_io = params[:file]
ext = uploaded_io.original_filename.split('.').last.downcase
unless uploaded_io.nil? || ['jpg', 'jpeg', 'tiff', 'gif', 'bmp'].include?(ext) == false
file_name = SecureRandom.hex(6) + '.' + ext
file_path = file_path + '/uploads/' + file_name
File.open(file_path, 'wb') do |file|
file.write(uploaded_io.read)
end
order = load_or_create_order
order.pictures.create(file_path: '/uploads/' + file_name, user_id: session[:user_id], caption: 'user upload')
return render json: { status: 'ok', file_path: '/uploads/' + file_name }
end
render json: { status: 'error', message: "Not a valid image file" }
end
def checkout
@order = Order.includes(:items).find_by(cart_key: cookies[:cart]) unless cookies[:cart].nil?
return redirect_to action: 'index' if (@order.nil? || @order.items.length == 0)
# check if login is required
if (session[:user_id].nil? && Cache.setting(Rails.configuration.domain_id, "eCommerce", "Checkout Require Login") == "true")
flash[:notice] = "Please log in to proceed with checkout"
return redirect_to "/login?redirect=/cart/checkout"
end
# retrieve info from previous order if user is logged in
if @order.user_id.nil? && !session[:user_id].nil?
@order.user_id = session[:user_id]
previous_order = Order.order('submitted DESC').find_by(user_id: @order.user_id, status: ['submitted', 'completed', 'shipped'])
unless previous_order.nil?
@order.shipping_name = previous_order.shipping_name
@order.shipping_street1 = previous_order.shipping_street1
@order.shipping_street2 = previous_order.shipping_street2
@order.shipping_city = previous_order.shipping_city
@order.shipping_state = previous_order.shipping_state
@order.shipping_zip = previous_order.shipping_zip
@order.shipping_country = previous_order.shipping_country
@order.notify_email = previous_order.notify_email
@order.contact_phone = previous_order.contact_phone
else
user = User.find(session[:user_id])
@order.notify_email = user.email
@order.contact_phone = user.phone
end
end
# set payment_method depending on total. PAYPAL would never reach this point
@order.payment_method = @order.total > 0.0 ? "CREDIT_CARD" : "NO_BILLING"
end
def checkout_update
@order = Order.includes(:items).find_by(cart_key: cookies[:cart]) unless cookies[:cart].nil?
return redirect_to action: 'index' if @order.nil? || @order.items.length == 0
@order.assign_attributes(order_params)
# update billing name otherwise credit card validation will fail
if @order.paid_with_card? && @order.same_as_shipping == '1'
@order.billing_name = @order.shipping_name
@order.billing_street1 = @order.shipping_street1
@order.billing_street2 = @order.shipping_street2
@order.billing_city = @order.shipping_city
@order.billing_state = @order.shipping_state
@order.billing_zip = @order.shipping_zip
@order.billing_country = @order.shipping_country
end
if @order.valid?
update_totals(@order)
@order.save(validate: false)
return redirect_to action: 'review'
end
render 'checkout'
end
def review
@order = Order.includes(:items).find_by(cart_key: cookies[:cart])
redirect_to action: 'index' if @order.nil? || @order.items.length == 0
end
def submit
@order = Order.includes(:items).find(params[:id])
@order.user_id = session[:user_id] if @order.user_id.nil? # attach order to logged-in user
@order.create_user if @order.user_id.nil?
# Double check if voucher is not being reused. this can happen if user has multiple
# carts in different browsers, all not check-out yet, but voucher applied, i.e. the
# voucher hasn't been marked as claimed yet.
unless @order.voucher_id.nil?
voucher = Voucher.find(@order.voucher_id)
if voucher.amount_used + @order.credit_applied > voucher.voucher_group.value
@order.errors.add :base, "Voucher has already been used. Please review changed to your order."
@order.voucher_id = nil
update_totals @order
@order.save
return render 'review'
end
end
# PROCESS PAYMENT
begin
@order.process_payment(request)
rescue => e
@order.errors.add :base, e.message
return render "review"
end
# IMPORTANT: save the order!
@order.save validate: false
# Do other stuff like deal counter updates, affiliate commission etc.
WebOrderJob.perform_later(order_id: @order.id,
email_blast_uuid: cookies[:ebuuid],
referral_key: cookies[:refkey],
affiliate_campaign_id: cookies[:acid])
# delete cart cookie and display confirmation
cookies.delete :cart
session[:order_id] = @order.id
redirect_to action: 'submitted', id: @order.id
end
def submitted
@order = Order.includes(:items).find(session[:order_id])
end
def applycode
# load order
applied = false
order = Order.includes(:items).find_by(cart_key: cookies[:cart])
# test if code is a coupon code
coupon = Coupon.find_by(code: params[:code])
unless coupon.nil?
applied = true
if (coupon.times_used > coupon.max_uses)
flash[:notice] = 'This coupon is no longer available.'
elsif coupon.start_time > Time.now || coupon.expire_time < Time.now
flash[:notice] = 'This coupon has expired.'
elsif coupon.min_order_amount && order.subtotal < coupon.min_order_amount
flash[:notice] = "This coupon is only valid for orders over #{number_to_currency(coupon.min_order_amount)}."
else
order.coupon_id = coupon.id
update_totals order
order.save validate: false
flash[:notice] = "Coupon code '#{coupon.code}' has been applied to your order."
end
# test if code is a voucher code
else
voucher = Voucher.find_by(code: params[:code])
unless voucher.nil?
if voucher.amount_used >= voucher.voucher_group.value
flash[:notice] = 'This voucher has already been claimed.'
elsif voucher.voucher_group.expires < Time.now
flash[:notice] = 'This voucher has expired.'
else
order.voucher_id = voucher.id
amt = voucher.voucher_group.value
update_totals order
order.save validate: false
applied = true
flash[:notice] = "A credit of $#{amt} has been applied to your order."
end
end
end
flash[:notice] = "Coupon or voucher code not found." unless applied
redirect_to :back
end
private
def order_params
params.require(:order).permit(:shipping_name, :shipping_street1, :shipping_street2, :shipping_city, :shipping_state,
:shipping_zip, :shipping_country, :contact_phone, :billing_name, :billing_street1, :billing_street2, :billing_city,
:billing_state, :billing_zip, :billing_country, :cc_type, :cc_number, :cc_expiration_month, :cc_expiration_year,
:cc_code, :notify_email, :customer_note, :payment_method, :same_as_shipping, :user_id)
end
end
|
require 'zip/zip'
class DocsController < ApplicationController
protect_from_forgery :except => [:create]
before_filter :authenticate_user!, :only => [:new, :edit, :new, :create, :create_project_docs, :update, :destroy, :project_delete_doc, :project_delete_all_docs]
# JSON POST
before_filter :http_basic_authenticate, :only => :create_project_docs, :if => Proc.new{|c| c.request.format == 'application/jsonrequest'}
skip_before_filter :authenticate_user!, :verify_authenticity_token, :if => Proc.new{|c| c.request.format == 'application/jsonrequest'}
autocomplete :doc, :sourcedb
def index
begin
@docs_count = Doc.where(serial: 0).count
@docs = if params[:keywords].present?
search_results = Doc.search_docs({body: params[:keywords].strip.downcase, page:params[:page]})
@search_count = search_results[:total]
search_results[:docs]
else
sort_order = sort_order(Doc)
Doc.where(serial: 0).sort_by_params(sort_order).paginate(:page => params[:page])
end
@sourcedbs = Doc.select(:sourcedb).distinct
respond_to do |format|
format.html
format.json {render json: docs_list_hash}
format.tsv {render text: Doc.to_tsv(source_docs_all, 'doc')}
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def index_in_project
begin
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
@docs_count = @project.docs.where(serial: 0).count
if params[:keywords].present?
search_results = Doc.search_docs({body: params[:keywords].strip.downcase, project_id: @project.id, page:params[:page]})
@search_count = search_results[:total]
@docs = search_results[:docs]
else
sort_order = sort_order(Doc)
@docs = @project.docs.where(serial: 0).sort_by_params(sort_order).paginate(:page => params[:page])
end
@sourcedbs = @project.docs.pluck(:sourcedb).uniq
respond_to do |format|
format.html
format.json {
source_docs_all = docs.where(serial: 0).sort_by_params(sort_order)
docs_list_hash = source_docs_all.map{|d| d.to_list_hash('doc')}
render json: docs_list_hash
}
format.tsv {
source_docs_all = docs.where(serial: 0).sort_by_params(sort_order)
render text: Doc.to_tsv(source_docs_all, 'doc')
}
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def records
if params[:project_id]
@project, notice = get_project(params[:project_id])
@new_doc_src = new_project_doc_path
if @project
@docs = @project.docs.order('sourcedb ASC').order('sourceid ASC').order('serial ASC')
else
@docs = nil
end
else
@docs = Doc.order('sourcedb ASC').order('sourceid ASC').order('serial ASC')
@new_doc_src = new_doc_path
end
@docs.each{|doc| doc.set_ascii_body} if (params[:encoding] == 'ascii')
respond_to do |format|
if @docs
format.html { @docs = @docs.paginate(:page => params[:page]) }
format.json { render json: @docs }
format.txt {
file_name = (@project)? @project.name + ".zip" : "docs.zip"
t = Tempfile.new("pubann-temp-filename-#{Time.now}")
Zip::ZipOutputStream.open(t.path) do |z|
@docs.each do |doc|
title = "%s-%s-%02d-%s" % [doc.sourcedb, doc.sourceid, doc.serial, doc.section]
title.sub!(/\.$/, '')
title.gsub!(' ', '_')
title += ".txt" unless title.end_with?(".txt")
z.put_next_entry(title)
z.print doc.body
end
end
send_file t.path, :type => 'application/zip',
:disposition => 'attachment',
:filename => file_name
t.close
# texts = @docs.collect{|doc| doc.body}
# render text: texts.join("\n----------\n")
}
else
format.html { flash[:notice] = notice }
format.json { head :unprocessable_entity }
format.txt { head :unprocessable_entity }
end
end
end
def sourcedb_index
if params[:project_id].present?
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
end
@sourcedb_doc_counts = if @project.present?
@project.docs.where("serial = ?", 0).group(:sourcedb).count
else
Doc.where("serial = ?", 0).group(:sourcedb).count
end
end
def sourceid_index
@sourcedb = params[:sourcedb]
if params[:project_id].present?
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
@docs_count = @project.docs.where(sourcedb: @sourcedb, serial: 0).count
@docs = @project.docs.where(sourcedb: @sourcedb, serial: 0).sort_by_params(sort_order(Doc)).paginate(:page => params[:page])
@search_path = search_project_docs_path(@project.name)
else
@docs_count = Doc.where(sourcedb: @sourcedb, serial: 0).count
@docs = Doc.where(sourcedb: @sourcedb, serial: 0).sort_by_params(sort_order(Doc)).paginate(:page => params[:page])
@search_path = search_docs_path
end
end
def show
begin
divs = if params[:id].present?
[Doc.find(params[:id])]
else
Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
end
raise "There is no such document." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to doc_sourcedb_sourceid_divs_index_path params}
format.json {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render json: divs.collect{|div| div.body}
}
format.txt {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render text: divs.collect{|div| div.body}.join("\n")
}
end
else
@doc = divs[0]
@doc.set_ascii_body if params[:encoding] == 'ascii'
@content = @doc.body.gsub(/\n/, "<br>")
@annotations = @doc.hannotations
@annotations[:denotations] = @annotations[:tracks].inject([]){|denotations, track| denotations += (track[:denotations] || [])}
@annotations[:relations] = @annotations[:tracks].inject([]){|relations, track| relations += (track[:relations] || [])}
@annotations[:modifications] = @annotations[:tracks].inject([]){|modifications, track| modifications += (track[:modifications] || [])}
sort_order = sort_order(Project)
@projects = @doc.projects.accessible(current_user).sort_by_params(sort_order)
respond_to do |format|
format.html
format.json {render json: @doc.to_hash}
format.txt {render text: @doc.body}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : docs_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def project_doc_show
begin
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
divs = @project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document in the project." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to index_project_sourcedb_sourceid_divs_docs_path(@project.name, params[:sourcedb], params[:sourceid])}
format.json {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render json: divs.collect{|div| div.body}
}
format.txt {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render text: divs.collect{|div| div.body}.join("\n")
}
end
else
@doc = divs[0]
@doc.set_ascii_body if (params[:encoding] == 'ascii')
@annotations = @doc.hannotations(@project)
@content = @doc.body.gsub(/\n/, "<br>")
@annotators = Annotator.all
@annotator_options = @annotators.map{|a| [a[:abbrev], a[:abbrev]]}
respond_to do |format|
format.html {render 'show_in_project'}
format.json {render json: @doc.to_hash}
format.txt {render text: @doc.body}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : docs_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render status: :unprocessable_entity}
end
end
end
def open
begin
project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless project.present?
divs = project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document in the project." unless divs.present?
respond_to do |format|
format.html {redirect_to show_project_sourcedb_sourceid_docs_path(params[:project_id], params[:sourcedb], params[:sourceid])}
end
rescue => e
respond_to do |format|
format.html {redirect_to :back, notice: e.message}
end
end
end
# GET /docs/new
# GET /docs/new.json
def new
@doc = Doc.new
begin
@project = get_project2(params[:project_id])
rescue => e
notice = e.message
end
respond_to do |format|
format.html # new.html.erb
format.json {render json: @doc.to_hash}
end
end
# GET /docs/1/edit
def edit
begin
@project = Project.editable(current_user).find_by_name(params[:project_id])
raise "There is no such project in your management." unless @project.present?
divs = @project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document in the project." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to index_project_sourcedb_sourceid_divs_docs_path(@project.name, params[:sourcedb], params[:sourceid])}
end
else
@doc = divs[0]
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : docs_path), notice: e.message}
end
end
@doc = Doc.find(params[:id])
end
# POST /docs
# POST /docs.json
# Creation of document is only allowed for single division documents.
def create
raise ArgumentError, "project id has to be specified." unless params[:project_id].present?
project = Project.editable(current_user).find_by_name(params[:project_id])
raise ArgumentError, "There is no such project in your management." unless project.present?
doc_hash = if params[:doc].present?
params[:doc]
else
{
source: params[:source],
sourcedb: params[:sourcedb] || '',
sourceid: params[:sourceid],
serial: params[:divid] || 0,
section: params[:section],
body: params[:text]
}
end
# sourcedb control
if doc_hash[:sourcedb].include?(Doc::UserSourcedbSeparator)
parts = doc_hash[:sourcedb].split(Doc::UserSourcedbSeparator)
raise ArgumentError, "'#{Doc::UserSourcedbSeparator}' is a special character reserved for separation of the username from a personal sourcedb name." unless parts.length == 2
raise ArgumentError, "'#{part[1]}' is not your username." unless parts[1] == current_user.username
else
doc_hash[:sourcedb] += "#{Doc::UserSourcedbSeparator}#{current_user.username}"
end
# sourceid control
unless doc_hash[:sourceid].present?
lastdoc = project.docs.where('sourcedb = ?', doc_hash[:sourcedb]).order("sourceid ASC").last
doc_hash[:sourceid] = lastdoc.nil? ? '1' : "#{lastdoc.sourceid.to_i + 1}"
end
@doc = Doc.new(doc_hash)
respond_to do |format|
if @doc.save
Doc.index_diff
@project, notice = get_project(params[:project_id])
@project.docs << @doc if @project.present?
get_project(params[:project_id])
format.html {
if @project.present?
redirect_to show_project_sourcedb_sourceid_docs_path(@project.name, doc_hash[:sourcedb], doc_hash[:sourceid]), notice: t('controllers.shared.successfully_created', :model => t('activerecord.models.doc'))
# redirect_to project_doc_path(@project.name, @doc), notice: t('controllers.shared.successfully_created', :model => t('activerecord.models.doc'))
else
redirect_to @doc, notice: t('controllers.shared.successfully_created', :model => t('activerecord.models.doc'))
end
}
format.json { render json: @doc, status: :created, location: @doc }
else
format.html { render action: "new" }
format.json { render json: @doc.errors, status: :unprocessable_entity }
end
end
end
# add new docs to a project
def add
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "There is no such project in your management." unless project.present?
# get the docspecs list
docspecs = if params["_json"] && params["_json"].class == Array
params["_json"].collect{|d| d.symbolize_keys}
elsif params["sourcedb"].present? && params["sourceid"].present?
[{sourcedb:params["sourcedb"], sourceid:params["sourceid"]}]
elsif params[:ids].present? && params[:sourcedb].present?
params[:ids].split(/[ ,"':|\t\n\r]+/).collect{|id| id.strip}.collect{|id| {sourcedb:params[:sourcedb], sourceid:id}}
else
[]
end
raise ArgumentError, "no valid document specification found." if docspecs.empty?
docspecs.each{|d| d[:sourceid].sub!(/^(PMC|pmc)/, '')}
docspecs.uniq!
if docspecs.length == 1
docspec = docspecs.first
begin
project.add_doc(docspec[:sourcedb], docspec[:sourceid], true)
message = "#{docspec[:sourcedb]}:#{docspec[:sourceid]} - added."
rescue => e
message = "#{docspec[:sourcedb]}:#{docspec[:sourceid]} - #{e.message}"
end
else
priority = project.jobs.unfinished.count
delayed_job = Delayed::Job.enqueue AddDocsToProjectJob.new(docspecs, project), priority: priority, queue: :general
Job.create({name:'Add docs to project', project_id:project.id, delayed_job_id:delayed_job.id})
message = "The task, 'add documents to the project', is created."
end
rescue => e
message = e.message
end
respond_to do |format|
format.html {redirect_to project_path(project.name), notice: message}
format.json {render json:{message:message}}
end
end
def uptodate
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
divs = params[:sourceid].present? ? Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid]) : nil
raise ArgumentError, "There is no such document." if params[:sourceid].present? && !divs.present?
Doc.uptodate(divs)
flash[:notice] = "The document #{divs[0].descriptor} is successfully updated."
rescue => e
flash[:notice] = e.message
end
redirect_to :back
end
# PUT /docs/1
# PUT /docs/1.json
def update
params[:doc][:body].gsub!(/\r\n/, "\n")
@doc = Doc.find(params[:id])
respond_to do |format|
if @doc.update_attributes(params[:doc])
format.html { redirect_to @doc, notice: t('controllers.shared.successfully_updated', :model => t('activerecord.models.doc')) }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @doc.errors, status: :unprocessable_entity }
end
end
end
# DELETE /docs/1
# DELETE /docs/1.json
def destroy
@doc = Doc.find(params[:id])
if params[:project_id].present?
project = Project.find_by_name(params[:project_id])
project.docs.delete(@doc)
redirect_path = records_project_docs_path(params[:project_id])
else
@doc.destroy
redirect_path = docs_url
end
respond_to do |format|
format.html { redirect_to redirect_path }
format.json { head :no_content }
end
end
def project_delete_doc
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "There is no such project in your management." unless project.present?
divs = project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document in the project." unless divs.present?
divs.each{|div| project.delete_doc(div, current_user)}
rescue => e
flash[:notice] = e
end
redirect_to :back
end
def store_span_rdf
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
system = Project.find_by_name('system-maintenance')
delayed_job = Delayed::Job.enqueue StoreRdfizedSpansJob.new(system, Pubann::Application.config.rdfizer_spans), queue: :general
Job.create({name:"Store RDFized spans for selected projects", project_id:system.id, delayed_job_id:delayed_job.id})
rescue => e
flash[:notice] = e.message
end
redirect_to project_path('system-maintenance')
end
# def autocomplete_sourcedb
# render :json => Doc.where(['LOWER(sourcedb) like ?', "%#{params[:term].downcase}%"]).collect{|doc| doc.sourcedb}.uniq
# end
end
FIXED uptodate redirect path
require 'zip/zip'
class DocsController < ApplicationController
protect_from_forgery :except => [:create]
before_filter :authenticate_user!, :only => [:new, :edit, :new, :create, :create_project_docs, :update, :destroy, :project_delete_doc, :project_delete_all_docs]
# JSON POST
before_filter :http_basic_authenticate, :only => :create_project_docs, :if => Proc.new{|c| c.request.format == 'application/jsonrequest'}
skip_before_filter :authenticate_user!, :verify_authenticity_token, :if => Proc.new{|c| c.request.format == 'application/jsonrequest'}
autocomplete :doc, :sourcedb
def index
begin
@docs_count = Doc.where(serial: 0).count
@docs = if params[:keywords].present?
search_results = Doc.search_docs({body: params[:keywords].strip.downcase, page:params[:page]})
@search_count = search_results[:total]
search_results[:docs]
else
sort_order = sort_order(Doc)
Doc.where(serial: 0).sort_by_params(sort_order).paginate(:page => params[:page])
end
@sourcedbs = Doc.select(:sourcedb).distinct
respond_to do |format|
format.html
format.json {render json: docs_list_hash}
format.tsv {render text: Doc.to_tsv(source_docs_all, 'doc')}
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def index_in_project
begin
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
@docs_count = @project.docs.where(serial: 0).count
if params[:keywords].present?
search_results = Doc.search_docs({body: params[:keywords].strip.downcase, project_id: @project.id, page:params[:page]})
@search_count = search_results[:total]
@docs = search_results[:docs]
else
sort_order = sort_order(Doc)
@docs = @project.docs.where(serial: 0).sort_by_params(sort_order).paginate(:page => params[:page])
end
@sourcedbs = @project.docs.pluck(:sourcedb).uniq
respond_to do |format|
format.html
format.json {
source_docs_all = docs.where(serial: 0).sort_by_params(sort_order)
docs_list_hash = source_docs_all.map{|d| d.to_list_hash('doc')}
render json: docs_list_hash
}
format.tsv {
source_docs_all = docs.where(serial: 0).sort_by_params(sort_order)
render text: Doc.to_tsv(source_docs_all, 'doc')
}
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def records
if params[:project_id]
@project, notice = get_project(params[:project_id])
@new_doc_src = new_project_doc_path
if @project
@docs = @project.docs.order('sourcedb ASC').order('sourceid ASC').order('serial ASC')
else
@docs = nil
end
else
@docs = Doc.order('sourcedb ASC').order('sourceid ASC').order('serial ASC')
@new_doc_src = new_doc_path
end
@docs.each{|doc| doc.set_ascii_body} if (params[:encoding] == 'ascii')
respond_to do |format|
if @docs
format.html { @docs = @docs.paginate(:page => params[:page]) }
format.json { render json: @docs }
format.txt {
file_name = (@project)? @project.name + ".zip" : "docs.zip"
t = Tempfile.new("pubann-temp-filename-#{Time.now}")
Zip::ZipOutputStream.open(t.path) do |z|
@docs.each do |doc|
title = "%s-%s-%02d-%s" % [doc.sourcedb, doc.sourceid, doc.serial, doc.section]
title.sub!(/\.$/, '')
title.gsub!(' ', '_')
title += ".txt" unless title.end_with?(".txt")
z.put_next_entry(title)
z.print doc.body
end
end
send_file t.path, :type => 'application/zip',
:disposition => 'attachment',
:filename => file_name
t.close
# texts = @docs.collect{|doc| doc.body}
# render text: texts.join("\n----------\n")
}
else
format.html { flash[:notice] = notice }
format.json { head :unprocessable_entity }
format.txt { head :unprocessable_entity }
end
end
end
def sourcedb_index
if params[:project_id].present?
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
end
@sourcedb_doc_counts = if @project.present?
@project.docs.where("serial = ?", 0).group(:sourcedb).count
else
Doc.where("serial = ?", 0).group(:sourcedb).count
end
end
def sourceid_index
@sourcedb = params[:sourcedb]
if params[:project_id].present?
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
@docs_count = @project.docs.where(sourcedb: @sourcedb, serial: 0).count
@docs = @project.docs.where(sourcedb: @sourcedb, serial: 0).sort_by_params(sort_order(Doc)).paginate(:page => params[:page])
@search_path = search_project_docs_path(@project.name)
else
@docs_count = Doc.where(sourcedb: @sourcedb, serial: 0).count
@docs = Doc.where(sourcedb: @sourcedb, serial: 0).sort_by_params(sort_order(Doc)).paginate(:page => params[:page])
@search_path = search_docs_path
end
end
def show
begin
divs = if params[:id].present?
[Doc.find(params[:id])]
else
Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
end
raise "There is no such document." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to doc_sourcedb_sourceid_divs_index_path params}
format.json {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render json: divs.collect{|div| div.body}
}
format.txt {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render text: divs.collect{|div| div.body}.join("\n")
}
end
else
@doc = divs[0]
@doc.set_ascii_body if params[:encoding] == 'ascii'
@content = @doc.body.gsub(/\n/, "<br>")
@annotations = @doc.hannotations
@annotations[:denotations] = @annotations[:tracks].inject([]){|denotations, track| denotations += (track[:denotations] || [])}
@annotations[:relations] = @annotations[:tracks].inject([]){|relations, track| relations += (track[:relations] || [])}
@annotations[:modifications] = @annotations[:tracks].inject([]){|modifications, track| modifications += (track[:modifications] || [])}
sort_order = sort_order(Project)
@projects = @doc.projects.accessible(current_user).sort_by_params(sort_order)
respond_to do |format|
format.html
format.json {render json: @doc.to_hash}
format.txt {render text: @doc.body}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : docs_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def project_doc_show
begin
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
divs = @project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document in the project." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to index_project_sourcedb_sourceid_divs_docs_path(@project.name, params[:sourcedb], params[:sourceid])}
format.json {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render json: divs.collect{|div| div.body}
}
format.txt {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render text: divs.collect{|div| div.body}.join("\n")
}
end
else
@doc = divs[0]
@doc.set_ascii_body if (params[:encoding] == 'ascii')
@annotations = @doc.hannotations(@project)
@content = @doc.body.gsub(/\n/, "<br>")
@annotators = Annotator.all
@annotator_options = @annotators.map{|a| [a[:abbrev], a[:abbrev]]}
respond_to do |format|
format.html {render 'show_in_project'}
format.json {render json: @doc.to_hash}
format.txt {render text: @doc.body}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : docs_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render status: :unprocessable_entity}
end
end
end
def open
begin
project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless project.present?
divs = project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document in the project." unless divs.present?
respond_to do |format|
format.html {redirect_to show_project_sourcedb_sourceid_docs_path(params[:project_id], params[:sourcedb], params[:sourceid])}
end
rescue => e
respond_to do |format|
format.html {redirect_to :back, notice: e.message}
end
end
end
# GET /docs/new
# GET /docs/new.json
def new
@doc = Doc.new
begin
@project = get_project2(params[:project_id])
rescue => e
notice = e.message
end
respond_to do |format|
format.html # new.html.erb
format.json {render json: @doc.to_hash}
end
end
# GET /docs/1/edit
def edit
begin
@project = Project.editable(current_user).find_by_name(params[:project_id])
raise "There is no such project in your management." unless @project.present?
divs = @project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document in the project." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to index_project_sourcedb_sourceid_divs_docs_path(@project.name, params[:sourcedb], params[:sourceid])}
end
else
@doc = divs[0]
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : docs_path), notice: e.message}
end
end
@doc = Doc.find(params[:id])
end
# POST /docs
# POST /docs.json
# Creation of document is only allowed for single division documents.
def create
raise ArgumentError, "project id has to be specified." unless params[:project_id].present?
project = Project.editable(current_user).find_by_name(params[:project_id])
raise ArgumentError, "There is no such project in your management." unless project.present?
doc_hash = if params[:doc].present?
params[:doc]
else
{
source: params[:source],
sourcedb: params[:sourcedb] || '',
sourceid: params[:sourceid],
serial: params[:divid] || 0,
section: params[:section],
body: params[:text]
}
end
# sourcedb control
if doc_hash[:sourcedb].include?(Doc::UserSourcedbSeparator)
parts = doc_hash[:sourcedb].split(Doc::UserSourcedbSeparator)
raise ArgumentError, "'#{Doc::UserSourcedbSeparator}' is a special character reserved for separation of the username from a personal sourcedb name." unless parts.length == 2
raise ArgumentError, "'#{part[1]}' is not your username." unless parts[1] == current_user.username
else
doc_hash[:sourcedb] += "#{Doc::UserSourcedbSeparator}#{current_user.username}"
end
# sourceid control
unless doc_hash[:sourceid].present?
lastdoc = project.docs.where('sourcedb = ?', doc_hash[:sourcedb]).order("sourceid ASC").last
doc_hash[:sourceid] = lastdoc.nil? ? '1' : "#{lastdoc.sourceid.to_i + 1}"
end
@doc = Doc.new(doc_hash)
respond_to do |format|
if @doc.save
Doc.index_diff
@project, notice = get_project(params[:project_id])
@project.docs << @doc if @project.present?
get_project(params[:project_id])
format.html {
if @project.present?
redirect_to show_project_sourcedb_sourceid_docs_path(@project.name, doc_hash[:sourcedb], doc_hash[:sourceid]), notice: t('controllers.shared.successfully_created', :model => t('activerecord.models.doc'))
# redirect_to project_doc_path(@project.name, @doc), notice: t('controllers.shared.successfully_created', :model => t('activerecord.models.doc'))
else
redirect_to @doc, notice: t('controllers.shared.successfully_created', :model => t('activerecord.models.doc'))
end
}
format.json { render json: @doc, status: :created, location: @doc }
else
format.html { render action: "new" }
format.json { render json: @doc.errors, status: :unprocessable_entity }
end
end
end
# add new docs to a project
def add
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "There is no such project in your management." unless project.present?
# get the docspecs list
docspecs = if params["_json"] && params["_json"].class == Array
params["_json"].collect{|d| d.symbolize_keys}
elsif params["sourcedb"].present? && params["sourceid"].present?
[{sourcedb:params["sourcedb"], sourceid:params["sourceid"]}]
elsif params[:ids].present? && params[:sourcedb].present?
params[:ids].split(/[ ,"':|\t\n\r]+/).collect{|id| id.strip}.collect{|id| {sourcedb:params[:sourcedb], sourceid:id}}
else
[]
end
raise ArgumentError, "no valid document specification found." if docspecs.empty?
docspecs.each{|d| d[:sourceid].sub!(/^(PMC|pmc)/, '')}
docspecs.uniq!
if docspecs.length == 1
docspec = docspecs.first
begin
project.add_doc(docspec[:sourcedb], docspec[:sourceid], true)
message = "#{docspec[:sourcedb]}:#{docspec[:sourceid]} - added."
rescue => e
message = "#{docspec[:sourcedb]}:#{docspec[:sourceid]} - #{e.message}"
end
else
priority = project.jobs.unfinished.count
delayed_job = Delayed::Job.enqueue AddDocsToProjectJob.new(docspecs, project), priority: priority, queue: :general
Job.create({name:'Add docs to project', project_id:project.id, delayed_job_id:delayed_job.id})
message = "The task, 'add documents to the project', is created."
end
rescue => e
message = e.message
end
respond_to do |format|
format.html {redirect_to project_path(project.name), notice: message}
format.json {render json:{message:message}}
end
end
def uptodate
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
divs = params[:sourceid].present? ? Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid]) : nil
raise ArgumentError, "There is no such document." if params[:sourceid].present? && !divs.present?
Doc.uptodate(divs)
flash[:notice] = "The document #{divs[0].descriptor} is successfully updated."
rescue => e
flash[:notice] = e.message
end
redirect_to doc_sourcedb_sourceid_show_path params
end
# PUT /docs/1
# PUT /docs/1.json
def update
params[:doc][:body].gsub!(/\r\n/, "\n")
@doc = Doc.find(params[:id])
respond_to do |format|
if @doc.update_attributes(params[:doc])
format.html { redirect_to @doc, notice: t('controllers.shared.successfully_updated', :model => t('activerecord.models.doc')) }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @doc.errors, status: :unprocessable_entity }
end
end
end
# DELETE /docs/1
# DELETE /docs/1.json
def destroy
@doc = Doc.find(params[:id])
if params[:project_id].present?
project = Project.find_by_name(params[:project_id])
project.docs.delete(@doc)
redirect_path = records_project_docs_path(params[:project_id])
else
@doc.destroy
redirect_path = docs_url
end
respond_to do |format|
format.html { redirect_to redirect_path }
format.json { head :no_content }
end
end
def project_delete_doc
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "There is no such project in your management." unless project.present?
divs = project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document in the project." unless divs.present?
divs.each{|div| project.delete_doc(div, current_user)}
rescue => e
flash[:notice] = e
end
redirect_to :back
end
def store_span_rdf
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
system = Project.find_by_name('system-maintenance')
delayed_job = Delayed::Job.enqueue StoreRdfizedSpansJob.new(system, Pubann::Application.config.rdfizer_spans), queue: :general
Job.create({name:"Store RDFized spans for selected projects", project_id:system.id, delayed_job_id:delayed_job.id})
rescue => e
flash[:notice] = e.message
end
redirect_to project_path('system-maintenance')
end
# def autocomplete_sourcedb
# render :json => Doc.where(['LOWER(sourcedb) like ?', "%#{params[:term].downcase}%"]).collect{|doc| doc.sourcedb}.uniq
# end
end
|
class DogsController < ApplicationController
def index
end
end
Green test: fetch all dogs
class DogsController < ApplicationController
def index
@dogs = Dog.all
end
end
|
class FishController < ApplicationController
def index
@fishes = Fish.all.reverse
end
def new
@fish = Fish.new
end
def create
@fish = Fish.create(fish_params)
@fish.update(:user => current_user)
redirect_to fish_index_path
end
private
def fish_params
params.require(:fish).permit(:species, :length, :weight, :location)
end
end
update fish controller for new attributes
class FishController < ApplicationController
def index
@fishes = Fish.all.reverse
end
def new
@fish = Fish.new
end
def create
@fish = Fish.create(fish_params)
@fish.update(:user => current_user)
redirect_to fish_index_path
end
private
def fish_params
params.require(:fish).permit(:species, :length, :latitude, :longitude, :weight, :location)
end
end
|
# ===GLSAMaker v2
# Copyright (C) 2010-11 Alex Legler <a3li@gentoo.org>
# Copyright (C) 2009 Pierre-Yves Rofes <py@gentoo.org>
#
# 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.
#
# For more information, see the LICENSE file.
# GLSA controller
class GlsaController < ApplicationController
def requests
@pageID = "requests"
@pageTitle = "Pooled GLSA requests"
@glsas = Glsa.where(:status => 'request').order('updated_at DESC')
end
def drafts
@pageID = "drafts"
@pageTitle = "Pooled GLSA drafts"
@glsas = Glsa.where(:status => 'draft').order('updated_at DESC')
end
def archive
@pageID = "archive"
@pageTitle = "GLSA archive"
respond_to do |format|
format.html {
@month = (params[:month] || Date.today.month).to_i
@year = (params[:year] || Date.today.year).to_i
month_start = Date.new(@year, @month, 1)
month_end = Date.new(@year, @month + 1, 1) - 1
@glsas = Glsa.where(:status => 'release', :first_released_at => month_start..month_end).order('updated_at DESC')
}
format.js {
@month = params[:view]['month(2i)'].to_i
@year = params[:view]['month(1i)'].to_i
month_start = Date.new(@year, @month, 1)
month_end = nil
if @month == 12
month_end = Date.new(@year + 1, 1, 1) -1
else
month_end = Date.new(@year, @month + 1, 1) - 1
end
@glsas = Glsa.where(:status => 'release', :first_released_at => month_start..month_end).order('updated_at DESC')
@table = render_to_string :partial => "glsa_row", :collection => @glsas, :as => :glsa, :locals => { :view => :drafts }
}
end
end
def new
@pageID = "new"
@pageTitle = "New GLSA"
# TODO: Straight-to-draft editing
render :action => "new-request"
return
if params[:what] == "request"
render :action => "new-request"
elsif params[:what] == "draft"
render :action => "new-draft"
else
render
end
end
def create
if params[:what] == "request"
begin
glsa = Glsa.new_request(params[:title], params[:bugs], params[:comment], params[:access], (params[:import_references].to_i == 1), current_user)
Glsamaker::Mail.request_notification(glsa, current_user)
flash[:notice] = "Successfully created GLSA #{glsa.glsa_id}"
redirect_to :action => "requests"
rescue Exception => e
log_error e
flash.now[:error] = e.message
render :action => "new-request"
end
end
end
def show
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = params[:rev_id].nil? ? @glsa.last_revision : @glsa.revisions.find_by_revid(params[:rev_id])
if @rev == nil
flash[:error] = "Invalid revision ID"
redirect_to :action => "show"
return
end
respond_to do |wants|
wants.html { render }
wants.xml { }
wants.txt { render }
end
end
def download
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = params[:rev_id].nil? ? @glsa.last_revision : @glsa.revisions.find_by_revid(params[:rev_id])
if @rev == nil
flash[:error] = "Invalid revision ID"
redirect_to :action => "show"
return
end
text = nil
respond_to do |wants|
wants.xml do
text = render_to_string(:action => :show, :format => 'xml')
send_data(text, :filename => "glsa-#{@glsa.glsa_id}.#{params[:format]}")
end
wants.txt do
text = render_to_string(:template => 'glsa/_email_headers.txt.erb', :format => 'txt')
text += render_to_string(:action => :show, :format => 'txt')
render :text => text
end
wants.html do
render :text => "Cannot download HTML format. Pick .xml or .txt"
return
end
end
end
def edit
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = @glsa.last_revision
set_up_editing
end
def update
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = @glsa.last_revision
if @glsa.nil?
flash[:error] = "Unknown GLSA ID"
redirect_to :action => "index"
return
end
# GLSA object
# The first editor is submitter, we assume he edits the description during that
if @glsa.submitter.nil? and params[:glsa][:description].strip != ""
@glsa.submitter = current_user
@glsa.status = "draft" if @glsa.status == "request"
end
@glsa.restricted = (params[:glsa][:restricted] == "confidential")
# Force update
@glsa.touch
revision = Revision.new
revision.revid = @glsa.next_revid
revision.glsa = @glsa
revision.user = current_user
revision.title = params[:glsa][:title]
revision.synopsis = params[:glsa][:synopsis]
revision.access = params[:glsa][:access]
revision.severity = params[:glsa][:severity]
revision.product = params[:glsa][:product]
revision.description = params[:glsa][:description]
revision.background = params[:glsa][:background]
revision.impact = params[:glsa][:impact]
revision.workaround = params[:glsa][:workaround]
revision.resolution = params[:glsa][:resolution]
unless revision.save
flash[:error] = "Errors occurred while saving the Revision object: #{revision.errors.full_messages.join ', '}"
set_up_editing
render :action => "edit"
return
end
unless @glsa.save
flash[:error] = "Errors occurred while saving the GLSA object"
set_up_editing
render :action => "edit"
return
end
# Bugs
bugzilla_warning = false
if params[:glsa][:bugs]
bugs = params[:glsa][:bugs].map {|bug| bug.to_i }
bugs.uniq.sort.each do |bug|
begin
b = Glsamaker::Bugs::Bug.load_from_id(bug)
revision.bugs.create!(
:bug_id => bug,
:title => b.summary,
:whiteboard => b.status_whiteboard,
:arches => b.arch_cc.join(', ')
)
rescue ActiveRecord::RecordInvalid => e
flash[:error] = "Errors occurred while saving a bug: #{e.record.errors.full_messages.join ', '}"
set_up_editing
render :action => "edit"
return
rescue Exception => e
log_error e
# In case of bugzilla errors, just keep the bug #
revision.bugs.create(
:bug_id => bug
)
bugzilla_warning = true
end
end
end
logger.debug "Packages: " + params[:glsa][:package].inspect
# Packages
packages = params[:glsa][:package] || []
packages.each do |package|
logger.debug package.inspect
next if package[:atom].strip == ''
begin
revision.packages.create!(package)
rescue ActiveRecord::RecordInvalid => e
flash[:error] = "Errors occurred while saving a package: #{e.record.errors.full_messages.join ', '}"
set_up_editing
render :action => "edit"
return
end
end
# References
unless params[:glsa][:reference].nil?
refs = params[:glsa][:reference].sort { |a, b| a[:title] <=> b[:title] }
refs.each do |reference|
logger.debug reference.inspect
next if reference[:title].strip == ''
# Special handling: Add CVE URL automatically
if reference[:title].strip =~ /^CVE-\d{4}-\d{4}/ and reference[:url].strip == ''
reference[:url] = "http://nvd.nist.gov/nvd.cfm?cvename=#{reference[:title].strip}"
end
begin
revision.references.create(reference)
rescue ActiveRecord::RecordInvalid => e
flash[:error] = "Errors occurred while saving a reference: #{e.record.errors.full_messages.join ', '}"
set_up_editing
render :action => "edit"
return
end
end
end
# Comments
@glsa.comments.each do |comment|
comment.read = params["commentread-#{comment.id}"] == "true"
comment.save
end
# Sending emails
Glsamaker::Mail.edit_notification(@glsa, rev_diff(@glsa, @glsa.revisions[-2], revision), current_user)
flash[:notice] = "Saving was successful. #{'NOTE: Bugzilla integration is not available, only plain bug numbers.' if bugzilla_warning}"
redirect_to :action => 'show', :id => @glsa
end
def prepare_release
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
if current_user.access < 2
deny_access "Tried to prepare release"
return
end
if @glsa.status == 'request'
flash[:error] = 'You cannot release a request. Draft the advisory first.'
redirect_to :action => "show", :id => @glsa
return
end
if @glsa.restricted
flash[:error] = 'You cannot release a confidential draft. Make it public first.'
redirect_to :action => "show", :id => @glsa
return
end
@rev = @glsa.last_revision
@comments_override = (current_user.is_el_jefe? and params[:override_approvals].to_i == 1) || false
end
def release
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
if current_user.access < 2
deny_access "Tried to prepare release"
return
end
if @glsa.status == 'request'
flash[:error] = 'You cannot release a request. Draft the advisory first.'
redirect_to :action => "show", :id => @glsa
return
end
if @glsa.restricted
flash[:error] = 'You cannot release a confidential draft. Make it public first.'
redirect_to :action => "show", :id => @glsa
return
end
@rev = @glsa.last_revision
begin
if current_user.is_el_jefe?
@glsa.release!
else
@glsa.release
end
@glsa.invalidate_last_revision_cache
if params[:email] == '1'
with_format('txt') do
Glsamaker::Mail.send_text(
render_to_string({:template => 'glsa/show.txt.erb', :layout => false}),
"[ GLSA #{@glsa.glsa_id} ] #{@rev.title}",
current_user,
false
)
end
end
rescue GLSAReleaseError => e
flash[:error] = "Internal error: #{e.message}. Cannot release advisory."
redirect_to :action => "show", :id => @glsa
return
end
# ugly hack, but necessary to switch back to html
@real_format = 'html'
render(:format => :html, :layout => 'application')
end
def finalize_release
@glsa = Glsa.find(params[:id])
if params[:close_bugs] == '1'
message = "GLSA #{@glsa.glsa_id}"
with_format(:txt) do
message = render_to_string :partial => 'close_msg'
end
@glsa.close_bugs(message)
end
end
def diff
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
rev_old = @glsa.revisions.find_by_revid(params[:old])
rev_new = @glsa.revisions.find_by_revid(params[:new])
@diff = with_format(:xml) { rev_diff(@glsa, rev_old, rev_new) }
end
def update_cache
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = @glsa.last_revision
@rev.update_cached_bug_metadata
flash[:notice] = "Successfully updated all caches."
if params[:redirect]
redirect_to params[:redirect]
else
redirect_to :action => 'show', :id => @glsa unless params[:no_redirect]
end
rescue Exception => e
log_error e
flash[:notice] = "Could not update caches: #{e.message}"
if params[:redirect]
redirect_to params[:redirect]
else
redirect_to :action => 'show', :id => @glsa unless params[:no_redirect]
end
end
def destroy
if !current_user.is_el_jefe?
deny_access "Cannot delete draft as non-admin user"
end
@glsa = Glsa.find(Integer(params[:id]))
@glsa.destroy
flash[:notice] = "GLSA successfully deleted."
redirect_to :controller => :index
end
def import_references
begin
if params[:go].to_s == '1'
glsa = Glsa.find(Integer(params[:id]))
return unless check_object_access!(glsa)
refs = []
params[:import][:cve].each do |cve_id|
cve = Cve.find_by_cve_id cve_id
refs << {:title => cve.cve_id, :url => cve.url}
end
refs = refs.sort { |a, b| a[:title] <=> b[:title] }
glsa.add_references refs
flash[:notice] = "Imported #{refs.count} references."
redirect_to :action => "show", :id => glsa.id
return
else
@glsa = Glsa.find(Integer(params[:id]))
return unless check_object_access!(@glsa)
@cves = @glsa.related_cves
end
rescue Exception => e
render :text => "Error: #{e.message}", :status => 500
log_error e
return
end
render :layout => false
end
protected
def set_up_editing
# Packages
@rev.vulnerable_packages.build(:comp => "<", :arch => "*") if @rev.vulnerable_packages.length == 0
@rev.unaffected_packages.build(:comp => ">=", :arch => "*") if @rev.unaffected_packages.length == 0
# References
if params.has_key? :glsa and params[:glsa].has_key? :reference
@references = []
params[:glsa][:reference].each do |reference|
@references << Reference.new(reference)
end
elsif @rev.references.length == 0
@references = [Reference.new]
else
@references = @rev.references
end
# Bugs
if params.has_key? :glsa and params[:glsa].has_key? :bugs
@bugs = []
params[:glsa][:bugs].each do |bug|
@bugs << Bug.new(:bug_id => bug)
end
else
@bugs = @rev.bugs
end
# Packages
if params.has_key? :glsa and params[:glsa].has_key? :package
@unaffected_packages = []
@vulnerable_packages = []
params[:glsa][:package].each do |package|
if package[:my_type] == 'vulnerable'
@vulnerable_packages << Package.new(package)
elsif package[:my_type] == 'unaffected'
@unaffected_packages << Package.new(package)
end
end
else
@unaffected_packages = @rev.unaffected_packages
@vulnerable_packages = @rev.vulnerable_packages
end
@templates = {}
GLSAMAKER_TEMPLATE_TARGETS.each do |target|
@templates[target] = Template.where(:target => target).all
end
end
def rev_diff(glsa, rev_old, rev_new, format = :unified, context_lines = 3)
@glsa = glsa
old_text = ""
unless rev_old.nil?
@rev = rev_old
old_text = Glsamaker::XML.indent(
render_to_string(
:template => 'glsa/_glsa.xml.builder',
:locals => {:glsa => @glsa, :rev => @rev},
:layout => 'none'
),
{:indent => 2, :maxcols => 80}
)
end
new_text = ""
unless rev_new.nil?
@rev = rev_new
new_text = Glsamaker::XML.indent(
render_to_string(
:template => 'glsa/_glsa.xml.builder',
:locals => {:glsa => @glsa, :rev => @rev},
:layout => 'none'
),
{:indent => 2, :maxcols => 80}
)
end
diff = ""
begin
diff = Glsamaker::Diff.diff(old_text, new_text, format, context_lines)
rescue Exception => e
diff = "Error in diff provider. Cannot provide diff."
log_error e
end
diff
end
end
Fix archive display in December. Thanks to ackle for the report
# ===GLSAMaker v2
# Copyright (C) 2010-11 Alex Legler <a3li@gentoo.org>
# Copyright (C) 2009 Pierre-Yves Rofes <py@gentoo.org>
#
# 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.
#
# For more information, see the LICENSE file.
# GLSA controller
class GlsaController < ApplicationController
def requests
@pageID = "requests"
@pageTitle = "Pooled GLSA requests"
@glsas = Glsa.where(:status => 'request').order('updated_at DESC')
end
def drafts
@pageID = "drafts"
@pageTitle = "Pooled GLSA drafts"
@glsas = Glsa.where(:status => 'draft').order('updated_at DESC')
end
def archive
@pageID = "archive"
@pageTitle = "GLSA archive"
respond_to do |format|
format.html {
@month = (params[:month] || Date.today.month).to_i
@year = (params[:year] || Date.today.year).to_i
month_start = Date.new(@year, @month, 1)
if @month == 12
month_end = Date.new(@year + 1, 1, 1) -1
else
month_end = Date.new(@year, @month + 1, 1) - 1
end
@glsas = Glsa.where(:status => 'release', :first_released_at => month_start..month_end).order('updated_at DESC')
}
format.js {
@month = params[:view]['month(2i)'].to_i
@year = params[:view]['month(1i)'].to_i
month_start = Date.new(@year, @month, 1)
month_end = nil
if @month == 12
month_end = Date.new(@year + 1, 1, 1) -1
else
month_end = Date.new(@year, @month + 1, 1) - 1
end
@glsas = Glsa.where(:status => 'release', :first_released_at => month_start..month_end).order('updated_at DESC')
@table = render_to_string :partial => "glsa_row", :collection => @glsas, :as => :glsa, :locals => { :view => :drafts }
}
end
end
def new
@pageID = "new"
@pageTitle = "New GLSA"
# TODO: Straight-to-draft editing
render :action => "new-request"
return
if params[:what] == "request"
render :action => "new-request"
elsif params[:what] == "draft"
render :action => "new-draft"
else
render
end
end
def create
if params[:what] == "request"
begin
glsa = Glsa.new_request(params[:title], params[:bugs], params[:comment], params[:access], (params[:import_references].to_i == 1), current_user)
Glsamaker::Mail.request_notification(glsa, current_user)
flash[:notice] = "Successfully created GLSA #{glsa.glsa_id}"
redirect_to :action => "requests"
rescue Exception => e
log_error e
flash.now[:error] = e.message
render :action => "new-request"
end
end
end
def show
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = params[:rev_id].nil? ? @glsa.last_revision : @glsa.revisions.find_by_revid(params[:rev_id])
if @rev == nil
flash[:error] = "Invalid revision ID"
redirect_to :action => "show"
return
end
respond_to do |wants|
wants.html { render }
wants.xml { }
wants.txt { render }
end
end
def download
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = params[:rev_id].nil? ? @glsa.last_revision : @glsa.revisions.find_by_revid(params[:rev_id])
if @rev == nil
flash[:error] = "Invalid revision ID"
redirect_to :action => "show"
return
end
text = nil
respond_to do |wants|
wants.xml do
text = render_to_string(:action => :show, :format => 'xml')
send_data(text, :filename => "glsa-#{@glsa.glsa_id}.#{params[:format]}")
end
wants.txt do
text = render_to_string(:template => 'glsa/_email_headers.txt.erb', :format => 'txt')
text += render_to_string(:action => :show, :format => 'txt')
render :text => text
end
wants.html do
render :text => "Cannot download HTML format. Pick .xml or .txt"
return
end
end
end
def edit
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = @glsa.last_revision
set_up_editing
end
def update
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = @glsa.last_revision
if @glsa.nil?
flash[:error] = "Unknown GLSA ID"
redirect_to :action => "index"
return
end
# GLSA object
# The first editor is submitter, we assume he edits the description during that
if @glsa.submitter.nil? and params[:glsa][:description].strip != ""
@glsa.submitter = current_user
@glsa.status = "draft" if @glsa.status == "request"
end
@glsa.restricted = (params[:glsa][:restricted] == "confidential")
# Force update
@glsa.touch
revision = Revision.new
revision.revid = @glsa.next_revid
revision.glsa = @glsa
revision.user = current_user
revision.title = params[:glsa][:title]
revision.synopsis = params[:glsa][:synopsis]
revision.access = params[:glsa][:access]
revision.severity = params[:glsa][:severity]
revision.product = params[:glsa][:product]
revision.description = params[:glsa][:description]
revision.background = params[:glsa][:background]
revision.impact = params[:glsa][:impact]
revision.workaround = params[:glsa][:workaround]
revision.resolution = params[:glsa][:resolution]
unless revision.save
flash[:error] = "Errors occurred while saving the Revision object: #{revision.errors.full_messages.join ', '}"
set_up_editing
render :action => "edit"
return
end
unless @glsa.save
flash[:error] = "Errors occurred while saving the GLSA object"
set_up_editing
render :action => "edit"
return
end
# Bugs
bugzilla_warning = false
if params[:glsa][:bugs]
bugs = params[:glsa][:bugs].map {|bug| bug.to_i }
bugs.uniq.sort.each do |bug|
begin
b = Glsamaker::Bugs::Bug.load_from_id(bug)
revision.bugs.create!(
:bug_id => bug,
:title => b.summary,
:whiteboard => b.status_whiteboard,
:arches => b.arch_cc.join(', ')
)
rescue ActiveRecord::RecordInvalid => e
flash[:error] = "Errors occurred while saving a bug: #{e.record.errors.full_messages.join ', '}"
set_up_editing
render :action => "edit"
return
rescue Exception => e
log_error e
# In case of bugzilla errors, just keep the bug #
revision.bugs.create(
:bug_id => bug
)
bugzilla_warning = true
end
end
end
logger.debug "Packages: " + params[:glsa][:package].inspect
# Packages
packages = params[:glsa][:package] || []
packages.each do |package|
logger.debug package.inspect
next if package[:atom].strip == ''
begin
revision.packages.create!(package)
rescue ActiveRecord::RecordInvalid => e
flash[:error] = "Errors occurred while saving a package: #{e.record.errors.full_messages.join ', '}"
set_up_editing
render :action => "edit"
return
end
end
# References
unless params[:glsa][:reference].nil?
refs = params[:glsa][:reference].sort { |a, b| a[:title] <=> b[:title] }
refs.each do |reference|
logger.debug reference.inspect
next if reference[:title].strip == ''
# Special handling: Add CVE URL automatically
if reference[:title].strip =~ /^CVE-\d{4}-\d{4}/ and reference[:url].strip == ''
reference[:url] = "http://nvd.nist.gov/nvd.cfm?cvename=#{reference[:title].strip}"
end
begin
revision.references.create(reference)
rescue ActiveRecord::RecordInvalid => e
flash[:error] = "Errors occurred while saving a reference: #{e.record.errors.full_messages.join ', '}"
set_up_editing
render :action => "edit"
return
end
end
end
# Comments
@glsa.comments.each do |comment|
comment.read = params["commentread-#{comment.id}"] == "true"
comment.save
end
# Sending emails
Glsamaker::Mail.edit_notification(@glsa, rev_diff(@glsa, @glsa.revisions[-2], revision), current_user)
flash[:notice] = "Saving was successful. #{'NOTE: Bugzilla integration is not available, only plain bug numbers.' if bugzilla_warning}"
redirect_to :action => 'show', :id => @glsa
end
def prepare_release
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
if current_user.access < 2
deny_access "Tried to prepare release"
return
end
if @glsa.status == 'request'
flash[:error] = 'You cannot release a request. Draft the advisory first.'
redirect_to :action => "show", :id => @glsa
return
end
if @glsa.restricted
flash[:error] = 'You cannot release a confidential draft. Make it public first.'
redirect_to :action => "show", :id => @glsa
return
end
@rev = @glsa.last_revision
@comments_override = (current_user.is_el_jefe? and params[:override_approvals].to_i == 1) || false
end
def release
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
if current_user.access < 2
deny_access "Tried to prepare release"
return
end
if @glsa.status == 'request'
flash[:error] = 'You cannot release a request. Draft the advisory first.'
redirect_to :action => "show", :id => @glsa
return
end
if @glsa.restricted
flash[:error] = 'You cannot release a confidential draft. Make it public first.'
redirect_to :action => "show", :id => @glsa
return
end
@rev = @glsa.last_revision
begin
if current_user.is_el_jefe?
@glsa.release!
else
@glsa.release
end
@glsa.invalidate_last_revision_cache
if params[:email] == '1'
with_format('txt') do
Glsamaker::Mail.send_text(
render_to_string({:template => 'glsa/show.txt.erb', :layout => false}),
"[ GLSA #{@glsa.glsa_id} ] #{@rev.title}",
current_user,
false
)
end
end
rescue GLSAReleaseError => e
flash[:error] = "Internal error: #{e.message}. Cannot release advisory."
redirect_to :action => "show", :id => @glsa
return
end
# ugly hack, but necessary to switch back to html
@real_format = 'html'
render(:format => :html, :layout => 'application')
end
def finalize_release
@glsa = Glsa.find(params[:id])
if params[:close_bugs] == '1'
message = "GLSA #{@glsa.glsa_id}"
with_format(:txt) do
message = render_to_string :partial => 'close_msg'
end
@glsa.close_bugs(message)
end
end
def diff
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
rev_old = @glsa.revisions.find_by_revid(params[:old])
rev_new = @glsa.revisions.find_by_revid(params[:new])
@diff = with_format(:xml) { rev_diff(@glsa, rev_old, rev_new) }
end
def update_cache
@glsa = Glsa.find(params[:id])
return unless check_object_access!(@glsa)
@rev = @glsa.last_revision
@rev.update_cached_bug_metadata
flash[:notice] = "Successfully updated all caches."
if params[:redirect]
redirect_to params[:redirect]
else
redirect_to :action => 'show', :id => @glsa unless params[:no_redirect]
end
rescue Exception => e
log_error e
flash[:notice] = "Could not update caches: #{e.message}"
if params[:redirect]
redirect_to params[:redirect]
else
redirect_to :action => 'show', :id => @glsa unless params[:no_redirect]
end
end
def destroy
if !current_user.is_el_jefe?
deny_access "Cannot delete draft as non-admin user"
end
@glsa = Glsa.find(Integer(params[:id]))
@glsa.destroy
flash[:notice] = "GLSA successfully deleted."
redirect_to :controller => :index
end
def import_references
begin
if params[:go].to_s == '1'
glsa = Glsa.find(Integer(params[:id]))
return unless check_object_access!(glsa)
refs = []
params[:import][:cve].each do |cve_id|
cve = Cve.find_by_cve_id cve_id
refs << {:title => cve.cve_id, :url => cve.url}
end
refs = refs.sort { |a, b| a[:title] <=> b[:title] }
glsa.add_references refs
flash[:notice] = "Imported #{refs.count} references."
redirect_to :action => "show", :id => glsa.id
return
else
@glsa = Glsa.find(Integer(params[:id]))
return unless check_object_access!(@glsa)
@cves = @glsa.related_cves
end
rescue Exception => e
render :text => "Error: #{e.message}", :status => 500
log_error e
return
end
render :layout => false
end
protected
def set_up_editing
# Packages
@rev.vulnerable_packages.build(:comp => "<", :arch => "*") if @rev.vulnerable_packages.length == 0
@rev.unaffected_packages.build(:comp => ">=", :arch => "*") if @rev.unaffected_packages.length == 0
# References
if params.has_key? :glsa and params[:glsa].has_key? :reference
@references = []
params[:glsa][:reference].each do |reference|
@references << Reference.new(reference)
end
elsif @rev.references.length == 0
@references = [Reference.new]
else
@references = @rev.references
end
# Bugs
if params.has_key? :glsa and params[:glsa].has_key? :bugs
@bugs = []
params[:glsa][:bugs].each do |bug|
@bugs << Bug.new(:bug_id => bug)
end
else
@bugs = @rev.bugs
end
# Packages
if params.has_key? :glsa and params[:glsa].has_key? :package
@unaffected_packages = []
@vulnerable_packages = []
params[:glsa][:package].each do |package|
if package[:my_type] == 'vulnerable'
@vulnerable_packages << Package.new(package)
elsif package[:my_type] == 'unaffected'
@unaffected_packages << Package.new(package)
end
end
else
@unaffected_packages = @rev.unaffected_packages
@vulnerable_packages = @rev.vulnerable_packages
end
@templates = {}
GLSAMAKER_TEMPLATE_TARGETS.each do |target|
@templates[target] = Template.where(:target => target).all
end
end
def rev_diff(glsa, rev_old, rev_new, format = :unified, context_lines = 3)
@glsa = glsa
old_text = ""
unless rev_old.nil?
@rev = rev_old
old_text = Glsamaker::XML.indent(
render_to_string(
:template => 'glsa/_glsa.xml.builder',
:locals => {:glsa => @glsa, :rev => @rev},
:layout => 'none'
),
{:indent => 2, :maxcols => 80}
)
end
new_text = ""
unless rev_new.nil?
@rev = rev_new
new_text = Glsamaker::XML.indent(
render_to_string(
:template => 'glsa/_glsa.xml.builder',
:locals => {:glsa => @glsa, :rev => @rev},
:layout => 'none'
),
{:indent => 2, :maxcols => 80}
)
end
diff = ""
begin
diff = Glsamaker::Diff.diff(old_text, new_text, format, context_lines)
rescue Exception => e
diff = "Error in diff provider. Cannot provide diff."
log_error e
end
diff
end
end
|
class HomeController < ApplicationController
def index
@users = User.all
end
end
assign recent votes in home index action
class HomeController < ApplicationController
def index
@recent_votes = Vote.get_recent_votes('senate')
end
end
|
class HomeController < ApplicationController
layout "application", :only => [ :about, :help ]
before_action :set_data_categories, only: [:index, :developers, :charts]
def index
colors = [
["rgba(255, 240, 110, 0.5)", "rgba(193, 186, 123, 0.5)"],
["rgba(187, 255, 147, 0.5)", "rgba(87, 149, 50, 0.5)"],
["rgba(147, 255, 220, 0.5)", "rgba(38, 113, 88, 0.5)"],
["rgba(255, 183, 147, 0.5)", "rgba(170, 95, 57, 0.5)"],
["rgba(255, 147, 172, 0.5)", "rgba(156, 52, 76, 0.5)"],
["rgba(147, 187, 255, 0.5)", "rgba(38, 87, 149, 0.5)"]
]
bus_usage_json = File.read("storage/#{ENV['place_code']}/buses/bus_usage.json")
bus_usage = JSON.parse(bus_usage_json)
@years = bus_usage.uniq { |p| p['Year'] }.collect { |p| p['Year'] }
# Months for looping over data
month_itter = ['January','February','March','April','May',
'June','July','August','September','October','November','December']
# Create a hash so you have bus_usage[year] containing an array of key-value pairs for month->value
bus_usage = Hash[*bus_usage.map { |k| [k['Year'], k] }.flatten]
@bus_data = []
@years.each do |year|
values = []
curr_usage = bus_usage[year]
month_itter.each do |month|
val = curr_usage[month]
# Only show it if it exists
if val != nil
values << val
else
values << 0
end
end
color = colors[colors.length - 1]
colors.delete_at(colors.length - 1)
@bus_data << { name: year, data: values, color: color[0], borderColor: color[1] }
end
@active_alerts = Alert.where(active: true).order(created_at: :desc)
respond_to do |format|
format.json
format.xml
format.html
end
end
def contact
end
def about
end
def help
end
def developers
end
def charts
end
def developers_data_category
@data_category = DataCategory.where("stub = ?", params[:data_category]).first
@data_sets = @data_category.data_sets.joins(:place).where("places.code = ?", ENV['place_code'].upcase)
end
def api
@data_category = DataCategory.where("stub = ?", params[:data_category]).first
@data_set = DataSet.joins(:place).where("stub = ? AND places.code = ? AND data_category_id = ?",
params[:data_set], ENV['place_code'].upcase, @data_category.id).first
# Live data is got from LiveDataSets in lib. The filename is set to the method name
# .send(...) calls a method via name.
if @data_set.live?
@data = LiveDataSets.send(@data_set.filename)
else
json = File.read("storage/#{ENV['place_code']}/#{@data_set.filename}")
@data = JSON.parse(json)
end
respond_to do |format|
format.json { render json: @data }
format.xml { @data }
format.html { render :api, layout: ((params[:layout].nil? || params[:layout] == 'true') ? true : false) }
end
end
def sitemap
set_data_categories
@data_sets = DataSet.all
respond_to do |format|
format.xml
end
end
private
def set_data_categories
@data_categories = DataCategory.all
@chart_categories = []
@data_categories.each do |data_category|
if path_exists? '/charts/' + data_category.stub
@chart_categories << data_category
end
end
end
def path_exists?(path)
begin
Rails.application.routes.recognize_path(path)
rescue
return false
end
true
end
end
Updated home to require live data set lib file. The catch all from /lib seems to have been ignored in rails 5... works locally though
require './lib/live_data_sets'
class HomeController < ApplicationController
layout "application", :only => [ :about, :help ]
before_action :set_data_categories, only: [:index, :developers, :charts]
def index
colors = [
["rgba(255, 240, 110, 0.5)", "rgba(193, 186, 123, 0.5)"],
["rgba(187, 255, 147, 0.5)", "rgba(87, 149, 50, 0.5)"],
["rgba(147, 255, 220, 0.5)", "rgba(38, 113, 88, 0.5)"],
["rgba(255, 183, 147, 0.5)", "rgba(170, 95, 57, 0.5)"],
["rgba(255, 147, 172, 0.5)", "rgba(156, 52, 76, 0.5)"],
["rgba(147, 187, 255, 0.5)", "rgba(38, 87, 149, 0.5)"]
]
bus_usage_json = File.read("storage/#{ENV['place_code']}/buses/bus_usage.json")
bus_usage = JSON.parse(bus_usage_json)
@years = bus_usage.uniq { |p| p['Year'] }.collect { |p| p['Year'] }
# Months for looping over data
month_itter = ['January','February','March','April','May',
'June','July','August','September','October','November','December']
# Create a hash so you have bus_usage[year] containing an array of key-value pairs for month->value
bus_usage = Hash[*bus_usage.map { |k| [k['Year'], k] }.flatten]
@bus_data = []
@years.each do |year|
values = []
curr_usage = bus_usage[year]
month_itter.each do |month|
val = curr_usage[month]
# Only show it if it exists
if val != nil
values << val
else
values << 0
end
end
color = colors[colors.length - 1]
colors.delete_at(colors.length - 1)
@bus_data << { name: year, data: values, color: color[0], borderColor: color[1] }
end
@active_alerts = Alert.where(active: true).order(created_at: :desc)
respond_to do |format|
format.json
format.xml
format.html
end
end
def contact
end
def about
end
def help
end
def developers
end
def charts
end
def developers_data_category
@data_category = DataCategory.where("stub = ?", params[:data_category]).first
@data_sets = @data_category.data_sets.joins(:place).where("places.code = ?", ENV['place_code'].upcase)
end
def api
@data_category = DataCategory.where("stub = ?", params[:data_category]).first
@data_set = DataSet.joins(:place).where("stub = ? AND places.code = ? AND data_category_id = ?",
params[:data_set], ENV['place_code'].upcase, @data_category.id).first
# Live data is got from LiveDataSets in lib. The filename is set to the method name
# .send(...) calls a method via name.
if @data_set.live?
@data = LiveDataSets.send(@data_set.filename)
else
json = File.read("storage/#{ENV['place_code']}/#{@data_set.filename}")
@data = JSON.parse(json)
end
respond_to do |format|
format.json { render json: @data }
format.xml { @data }
format.html { render :api, layout: ((params[:layout].nil? || params[:layout] == 'true') ? true : false) }
end
end
def sitemap
set_data_categories
@data_sets = DataSet.all
respond_to do |format|
format.xml
end
end
private
def set_data_categories
@data_categories = DataCategory.all
@chart_categories = []
@data_categories.each do |data_category|
if path_exists? '/charts/' + data_category.stub
@chart_categories << data_category
end
end
end
def path_exists?(path)
begin
Rails.application.routes.recognize_path(path)
rescue
return false
end
true
end
end
|
class HomeController < ApplicationController
caches_page :project_css
def index
notices_hash = Admin::SiteNotice.get_notices_for_user(current_user)
@notices = notices_hash[:notices]
@notice_display_type = notices_hash[:notice_display_type]
end
def readme
@document = FormattedDoc.new('README.textile')
render :action => "formatted_doc", :layout => "technical_doc"
end
def doc
if document_path = params[:document].gsub(/\.\.\//, '')
@document = FormattedDoc.new(File.join('doc', document_path))
render :action => "formatted_doc", :layout => "technical_doc"
end
end
def pick_signup
end
def about
end
def requirements
end
# view_context is a reference to the View template object
def name_for_clipboard_data
render :text=> view_context.clipboard_object_name(params)
end
def missing_installer
@os = params['os']
end
def test_exception
raise 'This is a test. This is only a test.'
end
def project_css
@project = Admin::Project.default_project
if @project.using_custom_css?
render :text => @project.custom_css
else
render :nothing => true, :status => 404
end
end
def report
# two different ways to render pdfs
respond_to do |format|
# this method uses classes in app/pdfs to generate the pdf:
format.html {
output = ::HelloReport.new.to_pdf
send_data output, :filename => "hello1.pdf", :type => "application/pdf"
}
# this method uses the prawn-rails gem to render the view:
# app/views/home/report.pdf.prawn
# see: https://github.com/Volundr/prawn-rails
format.pdf { render :layout => false }
end
end
# def index
# if current_user.require_password_reset
# redirect_to :controller => :passwords, :action=>'reset', :reset_code => 0
# end
# end
def recent_activity
if current_user.anonymous?
redirect_to home_url
return
end
@report_learner = Report::Learner.all
teacher_clazzes = current_user.portal_teacher.clazzes;
portal_teacher_clazzes = current_user.portal_teacher.teacher_clazzes
portal_teacher_offerings = [];
teacher_clazzes.each do|teacher_clazz|
if portal_teacher_clazzes.find_by_clazz_id(teacher_clazz.id).active && teacher_clazz.students.length > 0
portal_teacher_offerings.concat(teacher_clazz.offerings)
end
end
time_limit = Report::Learner.order("last_run DESC").first.last_run - 7.days
learner_offerings = (Report::Learner.where("last_run > '#{time_limit}' and complete_percent > 0").order("last_run DESC")).select(:offering_id).uniq
@clazz_offerings=Array.new
learner_offerings.each do |learner_offering|
portal_teacher_offerings.each do|teacher_offering|
reportlearner = Report::Learner.find_by_offering_id(learner_offering.offering_id)
if reportlearner.offering_id == teacher_offering.id
offering = Portal::Offering.find(reportlearner.offering_id)
if offering.inprogress_students_count > 0 || offering.completed_students_count > 0
@clazz_offerings.push(offering)
end
end
end
end
notices_hash = Admin::SiteNotice.get_notices_for_user(current_user)
@notices = notices_hash[:notices]
@notice_display_type = notices_hash[:notice_display_type]
if (@clazz_offerings.count == 0)
redirect_to root_path
return
end
end
end
Check for nils in the Recent Activity filters
- Check for nils in the Recent Activity filters
- Conflicts:
app/controllers/home_controller.rb
class HomeController < ApplicationController
caches_page :project_css
def index
notices_hash = Admin::SiteNotice.get_notices_for_user(current_user)
@notices = notices_hash[:notices]
@notice_display_type = notices_hash[:notice_display_type]
end
def readme
@document = FormattedDoc.new('README.textile')
render :action => "formatted_doc", :layout => "technical_doc"
end
def doc
if document_path = params[:document].gsub(/\.\.\//, '')
@document = FormattedDoc.new(File.join('doc', document_path))
render :action => "formatted_doc", :layout => "technical_doc"
end
end
def pick_signup
end
def about
end
def requirements
end
# view_context is a reference to the View template object
def name_for_clipboard_data
render :text=> view_context.clipboard_object_name(params)
end
def missing_installer
@os = params['os']
end
def test_exception
raise 'This is a test. This is only a test.'
end
def project_css
@project = Admin::Project.default_project
if @project.using_custom_css?
render :text => @project.custom_css
else
render :nothing => true, :status => 404
end
end
def report
# two different ways to render pdfs
respond_to do |format|
# this method uses classes in app/pdfs to generate the pdf:
format.html {
output = ::HelloReport.new.to_pdf
send_data output, :filename => "hello1.pdf", :type => "application/pdf"
}
# this method uses the prawn-rails gem to render the view:
# app/views/home/report.pdf.prawn
# see: https://github.com/Volundr/prawn-rails
format.pdf { render :layout => false }
end
end
# def index
# if current_user.require_password_reset
# redirect_to :controller => :passwords, :action=>'reset', :reset_code => 0
# end
# end
def recent_activity
if current_user.anonymous?
redirect_to home_url
return
end
@report_learner = Report::Learner.all
teacher_clazzes = current_user.portal_teacher.clazzes;
portal_teacher_clazzes = current_user.portal_teacher.teacher_clazzes
portal_teacher_offerings = [];
teacher_clazzes.each do|teacher_clazz|
if portal_teacher_clazzes.find_by_clazz_id(teacher_clazz.id).active && teacher_clazz.students.length > 0
portal_teacher_offerings.concat(teacher_clazz.offerings)
end
end
latest_report_learner = Report::Learner.order("last_run DESC").first
unless latest_report_learner
# There are no report learners
redirect_to root_path
return
end
time_limit = latest_report_learner.last_run - 7.days
learner_offerings = (Report::Learner.where("last_run > '#{time_limit}' and complete_percent > 0").order("last_run DESC")).select(:offering_id).uniq
# There are no report learners for this filter
@clazz_offerings=Array.new
learner_offerings.each do |learner_offering|
portal_teacher_offerings.each do|teacher_offering|
reportlearner = Report::Learner.find_by_offering_id(learner_offering.offering_id)
if reportlearner.offering_id == teacher_offering.id
offering = Portal::Offering.find(reportlearner.offering_id)
if offering.inprogress_students_count > 0 || offering.completed_students_count > 0
@clazz_offerings.push(offering)
end
end
end
end
notices_hash = Admin::SiteNotice.get_notices_for_user(current_user)
@notices = notices_hash[:notices]
@notice_display_type = notices_hash[:notice_display_type]
if (@clazz_offerings.count == 0)
redirect_to root_path
return
end
end
end
|
class HomeController < ApplicationController
require 'yaml'
require 'pry'
def index
end
def investigate
if session[:a] || session[:b]
a = session[:a]
b = session[:b]
session[:a] = session[:b] = nil
else
a = params[:a]
b = params[:b]
end
unless current_user
session[:a] = a
session[:b] = b
redirect_to "/auth/twitter"
return
end
# now logged in
puts "----------------------now logged in "
begin
c = current_user.client
a_user = c.user a
b_user = c.user b
a_uid = a_user.attrs["id"]
b_uid = b_user.attrs["id"]
@a = a_user.attrs["screen_name"]
@b = b_user.attrs["screen_name"]
a_target = Target.find_or_create a_uid
b_target = Target.find_or_create b_uid
puts "----------------------target set"
a_th = Thread.new {a_target.fill(current_user)}
b_target.fill(current_user)
a_th.join
puts "----------------------filled"
a_samples = YAML::load(a_target.samples)
b_samples = YAML::load(b_target.samples)
puts "----------------------loaded "
@pval = kentei(a_samples, b_samples)
rescue Twitter::Error::Unauthorized
session[:user_id] = nil
redirect_to root_url
rescue Twitter::Error::NotFound
session[:notice] = "not found"
redirect_to root_url
end
end
private
def kentei(a_arr, b_arr)
require "rinruby"
require 'set'
kara = [a_arr[0], b_arr[0]].max
made = [a_arr[-1],b_arr[-1]].min
raise Exception if kara > made
a_set = Set.new a_arr
b_set = Set.new b_arr
range = []
tmp = kara
while tmp <= made
range = range + [tmp]
tmp += DateTime.tanni
end
# now use R
R.assign "a_row", (as = range.collect {|t| if a_set.include? t then 1 else 0 end})
R.assign "b_row", (bs = range.collect {|t| if b_set.include? t then 1 else 0 end})
R.assign "c_row", (range.collect {|t| t.hour})
return 0.0 if as == bs && as.length > 5
R.eval "y.data <- data.frame( as = a_row, bs = b_row, cs = c_row )"
R.eval "library(ppcor)"
# want to call pry
# binding.pry
begin
results = R.pull 'as.numeric(pcor.test(y.data$as,y.data$bs,y.data[,c("cs")]))'
rescue NoMethodError
results = [nil,nil]
end
return results[1]
end
end
rate limit exceeded
class HomeController < ApplicationController
require 'yaml'
require 'pry'
def index
end
def investigate
if session[:a] || session[:b]
a = session[:a]
b = session[:b]
session[:a] = session[:b] = nil
else
a = params[:a]
b = params[:b]
end
unless current_user
session[:a] = a
session[:b] = b
redirect_to "/auth/twitter"
return
end
# now logged in
puts "----------------------now logged in "
begin
c = current_user.client
a_user = c.user a
b_user = c.user b
a_uid = a_user.attrs["id"]
b_uid = b_user.attrs["id"]
@a = a_user.attrs["screen_name"]
@b = b_user.attrs["screen_name"]
a_target = Target.find_or_create a_uid
b_target = Target.find_or_create b_uid
puts "----------------------target set"
a_th = Thread.new {a_target.fill(current_user)}
b_target.fill(current_user)
a_th.join
puts "----------------------filled"
a_samples = YAML::load(a_target.samples)
b_samples = YAML::load(b_target.samples)
puts "----------------------loaded "
@pval = kentei(a_samples, b_samples)
rescue Twitter::Error::Unauthorized
session[:user_id] = nil
redirect_to root_url
rescue Twitter::Error::NotFound
session[:notice] = "not found"
redirect_to root_url
rescue Twitter::Error::BadRequest
session[:notice] = "tsukai sugi?"
redirect_to root_url
end
end
private
def kentei(a_arr, b_arr)
require "rinruby"
require 'set'
kara = [a_arr[0], b_arr[0]].max
made = [a_arr[-1],b_arr[-1]].min
raise Exception if kara > made
a_set = Set.new a_arr
b_set = Set.new b_arr
range = []
tmp = kara
while tmp <= made
range = range + [tmp]
tmp += DateTime.tanni
end
# now use R
R.assign "a_row", (as = range.collect {|t| if a_set.include? t then 1 else 0 end})
R.assign "b_row", (bs = range.collect {|t| if b_set.include? t then 1 else 0 end})
R.assign "c_row", (range.collect {|t| t.hour})
return 0.0 if as == bs && as.length > 5
R.eval "y.data <- data.frame( as = a_row, bs = b_row, cs = c_row )"
R.eval "library(ppcor)"
# want to call pry
# binding.pry
begin
results = R.pull 'as.numeric(pcor.test(y.data$as,y.data$bs,y.data[,c("cs")]))'
rescue NoMethodError
results = [nil,nil]
end
return results[1]
end
end
|
class HostController < ApplicationController
before_action :check_privileges
before_action :get_session_data
after_action :cleanup_action
after_action :set_session_data
def index
redirect_to :action => 'show_list'
end
def show_association(action, display_name, listicon, method, klass, association = nil, conditions = nil)
set_config(identify_record(params[:id]))
super
end
def show
return if perfmenu_click?
@lastaction = "show"
@showtype = "config"
@display = params[:display] || "main" unless control_selected?
@host = @record = identify_record(params[:id])
return if record_no_longer_exists?(@host, 'Host')
@gtl_url = "/host/show/" << @host.id.to_s << "?"
@showtype = "config"
set_config(@host)
case @display
when "download_pdf", "main", "summary_only"
get_tagdata(@host)
drop_breadcrumb({:name => "Hosts", :url => "/host/show_list?page=#{@current_page}&refresh=y"}, true)
drop_breadcrumb(:name => @host.name + " (Summary)", :url => "/host/show/#{@host.id}")
@showtype = "main"
set_summary_pdf_data if ["download_pdf", "summary_only"].include?(@display)
when "devices"
drop_breadcrumb(:name => @host.name + " (Devices)", :url => "/host/show/#{@host.id}?display=devices")
when "os_info"
drop_breadcrumb(:name => @host.name + " (OS Information)", :url => "/host/show/#{@host.id}?display=os_info")
when "hv_info"
drop_breadcrumb(:name => @host.name + " (VM Monitor Information)", :url => "/host/show/#{@host.id}?display=hv_info")
when "network"
drop_breadcrumb(:name => @host.name + " (Network)", :url => "/host/show/#{@host.id}?display=network")
build_network_tree
when "performance"
@showtype = "performance"
drop_breadcrumb(:name => "#{@host.name} Capacity & Utilization", :url => "/host/show/#{@host.id}?display=#{@display}&refresh=n")
perf_gen_init_options # Intialize perf chart options, charts will be generated async
when "timeline"
@showtype = "timeline"
session[:tl_record_id] = params[:id] if params[:id]
@record = find_by_id_filtered(Host, session[:tl_record_id])
@timeline = @timeline_filter = true
@lastaction = "show_timeline"
tl_build_timeline # Create the timeline report
drop_breadcrumb(:name => "Timelines", :url => "/host/show/#{@record.id}?refresh=n&display=timeline")
when "compliance_history"
count = params[:count] ? params[:count].to_i : 10
session[:ch_tree] = compliance_history_tree(@host, count).to_json
session[:tree_name] = "ch_tree"
session[:squash_open] = (count == 1)
drop_breadcrumb({:name => @host.name, :url => "/host/show/#{@host.id}"}, true)
if count == 1
drop_breadcrumb(:name => @host.name + " (Latest Compliance Check)", :url => "/host/show/#{@host.id}?display=#{@display}")
else
drop_breadcrumb(:name => @host.name + " (Compliance History - Last #{count} Checks)", :url => "/host/show/#{@host.id}?display=#{@display}")
end
@showtype = @display
when "storage_adapters"
drop_breadcrumb(:name => @host.name + " (Storage Adapters)", :url => "/host/show/#{@host.id}?display=storage_adapters")
build_sa_tree
when "miq_templates", "vms"
title = @display == "vms" ? "VMs" : "Templates"
kls = @display == "vms" ? Vm : MiqTemplate
drop_breadcrumb(:name => @host.name + " (All #{title})", :url => "/host/show/#{@host.id}?display=#{@display}")
@view, @pages = get_view(kls, :parent => @host) # Get the records (into a view) and the paginator
@showtype = @display
if @view.extras[:total_count] && @view.extras[:auth_count] &&
@view.extras[:total_count] > @view.extras[:auth_count]
@bottom_msg = "* You are not authorized to view " + pluralize(@view.extras[:total_count] - @view.extras[:auth_count], "other #{title.singularize}") + " on this Host"
end
when "cloud_tenants"
drop_breadcrumb(:name => _("%s (All cloud tenants present on this host)") % @host.name,
:url => "/host/show/#{@host.id}?display=cloud_tenants")
@view, @pages = get_view(CloudTenant, :parent => @host) # Get the records (into a view) and the paginator
@showtype = "cloud_tenants"
when "resource_pools"
drop_breadcrumb(:name => @host.name + " (All Resource Pools)", :url => "/host/show/#{@host.id}?display=resource_pools")
@view, @pages = get_view(ResourcePool, :parent => @host) # Get the records (into a view) and the paginator
@showtype = "resource_pools"
when "storages"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "storages")})", :url => "/host/show/#{@host.id}?display=storages")
@view, @pages = get_view(Storage, :parent => @host) # Get the records (into a view) and the paginator
@showtype = "storages"
if @view.extras[:total_count] && @view.extras[:auth_count] &&
@view.extras[:total_count] > @view.extras[:auth_count]
@bottom_msg = "* You are not authorized to view " + pluralize(@view.extras[:total_count] - @view.extras[:auth_count], "other " + ui_lookup(:table => "storages")) + " on this Host"
end
when "ontap_logical_disks"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "ontap_logical_disk")})", :url => "/host/show/#{@host.id}?display=ontap_logicals_disks")
@view, @pages = get_view(OntapLogicalDisk, :parent => @host, :parent_method => :logical_disks) # Get the records (into a view) and the paginator
@showtype = "ontap_logicals_disks"
when "ontap_storage_systems"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "ontap_storage_system")})", :url => "/host/show/#{@host.id}?display=ontap_storage_systems")
@view, @pages = get_view(OntapStorageSystem, :parent => @host, :parent_method => :storage_systems) # Get the records (into a view) and the paginator
@showtype = "ontap_storage_systems"
when "ontap_storage_volumes"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "ontap_storage_volume")})", :url => "/host/show/#{@host.id}?display=ontap_storage_volumes")
@view, @pages = get_view(OntapStorageVolume, :parent => @host, :parent_method => :storage_volumes) # Get the records (into a view) and the paginator
@showtype = "ontap_storage_volumes"
when "ontap_file_shares"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "ontap_file_share")})", :url => "/host/show/#{@host.id}?display=ontap_file_shares")
@view, @pages = get_view(OntapFileShare, :parent => @host, :parent_method => :file_shares) # Get the records (into a view) and the paginator
@showtype = "ontap_file_shares"
end
@lastaction = "show"
session[:tl_record_id] = @record.id
# Came in from outside show_list partial
if params[:ppsetting] || params[:searchtag] || params[:entry] || params[:sort_choice]
replace_gtl_main_div
end
end
def filesystems_subsets
condition = nil
label = _('Files')
host_service_group = HostServiceGroup.where(:id => params['host_service_group']).first
if host_service_group
condition = host_service_group.host_service_group_filesystems_condition
label = _("Configuration files of %s") % 'nova service'
end
# HACK: UI get_view can't do arel relations, so I need to expose conditions
condition = condition.to_sql if condition
return label, condition
end
def set_config_local
set_config(identify_record(params[:id]))
super
end
alias_method :set_config_local, :drift_history
alias_method :set_config_local, :groups
alias_method :set_config_local, :patches
alias_method :set_config_local, :users
def filesystems
label, condition = filesystems_subsets
show_association('filesystems', label, 'filesystems', :filesystems, Filesystem, nil, condition)
end
def host_services_subsets
condition = nil
label = _('Services')
host_service_group = HostServiceGroup.where(:id => params['host_service_group']).first
if host_service_group
case params[:status]
when 'running'
condition = host_service_group.running_system_services_condition
label = _("Running system services of %s") % host_service_group.name
when 'failed'
condition = host_service_group.failed_system_services_condition
label = _("Failed system services of %s") % host_service_group.name
when 'all'
condition = nil
label = _("All system services of %s") % host_service_group.name
end
if condition
# Amend the condition with the openstack host service foreign key
condition = condition.and(host_service_group.host_service_group_system_services_condition)
else
condition = host_service_group.host_service_group_system_services_condition
end
end
# HACK: UI get_view can't do arel relations, so I need to expose conditions
condition = condition.to_sql if condition
return label, condition
end
def host_services
label, condition = host_services_subsets
show_association('host_services', label, 'service', :host_services, SystemService, nil, condition)
end
def advanced_settings
show_association('advanced_settings', 'Advanced Settings', 'advancedsetting', :advanced_settings, AdvancedSetting)
end
def firewall_rules
@display = "main"
show_association('firewall_rules', 'Firewall Rules', 'firewallrule', :firewall_rules, FirewallRule)
end
def guest_applications
show_association('guest_applications', 'Packages', 'guest_application', :guest_applications, GuestApplication)
end
def toggle_policy_profile
if session[:policy_assignment_compressed].nil?
session[:policy_assignment_compressed] = false
else
session[:policy_assignment_compressed] = !session[:policy_assignment_compressed]
end
@compressed = session[:policy_assignment_compressed]
protect_build_screen
protect_set_db_record
render :update do |page| # Use RJS to update the display
page.replace_html("view_buttons_div", :partial => "layouts/view_buttons") # Replace the view buttons
page.replace_html("main_div", :partial => "layouts/protecting") # Replace the main div area contents
end
end
# Show the main Host list view
def show_list
session[:host_items] = nil
process_show_list
end
def start
redirect_to :action => 'show_list'
end
def new
assert_privileges("host_new")
@host = Host.new
@in_a_form = true
drop_breadcrumb(:name => "Add New Host", :url => "/host/new")
end
def create
assert_privileges("host_new")
case params[:button]
when "cancel"
render :update do |page|
page.redirect_to :action => 'show_list', :flash_msg => _("Add of new %s was cancelled by the user") % ui_lookup(:model => "Host")
end
when "add"
@host = Host.new
old_host_attributes = @host.attributes.clone
set_record_vars(@host, :validate) # Set the record variables, but don't save
@host.vmm_vendor = "unknown"
if valid_record?(@host) && @host.save
set_record_vars(@host) # Save the authentication records for this host
AuditEvent.success(build_saved_audit_hash_angular(old_host_attributes, @host, params[:button] == "add"))
message = _("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => "Host"), :name => @host.name}
render :update do |page|
page.redirect_to :action => 'show_list',
:flash_msg => message
end
else
@in_a_form = true
@errors.each { |msg| add_flash(msg, :error) }
@host.errors.each do |field, msg|
add_flash("#{field.to_s.capitalize} #{msg}", :error)
end
drop_breadcrumb(:name => "Add New Host", :url => "/host/new")
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
when "validate"
verify_host = Host.new
set_record_vars(verify_host, :validate)
@in_a_form = true
begin
verify_host.verify_credentials(params[:type])
rescue StandardError => bang
add_flash("#{bang}", :error)
else
add_flash(_("Credential validation was successful"))
end
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
end
def edit
assert_privileges("host_edit")
if session[:host_items].nil?
@host = find_by_id_filtered(Host, params[:id])
@in_a_form = true
session[:changed] = false
drop_breadcrumb(:name => "Edit Host '#{@host.name}'", :url => "/host/edit/#{@host.id}")
@title = "Info/Settings"
else # if editing credentials for multi host
@title = "Credentials/Settings"
if params[:selected_host]
@host = find_by_id_filtered(Host, params[:selected_host])
else
@host = Host.new
end
@changed = true
@showlinks = true
@in_a_form = true
# Get the db records that are being tagged
hostitems = Host.find(session[:host_items]).sort { |a, b| a.name <=> b.name }
@selected_hosts = {}
hostitems.each do |h|
@selected_hosts[h.id] = h.name
end
build_targets_hash(hostitems)
@view = get_db_view(Host) # Instantiate the MIQ Report view object
@view.table = MiqFilter.records2table(hostitems, :only => @view.cols + ['id'])
end
end
def update
assert_privileges("host_edit")
case params[:button]
when "cancel"
session[:edit] = nil # clean out the saved info
flash = "Edit for Host \""
@breadcrumbs.pop if @breadcrumbs
if !session[:host_items].nil?
flash = _("Edit of credentials for selected %s was cancelled by the user") % ui_lookup(:models => "Host")
# redirect_to :action => @lastaction, :display=>session[:host_display], :flash_msg=>flash
render :update do |page|
page.redirect_to :action => @lastaction, :display => session[:host_display], :flash_msg => flash
end
else
@host = find_by_id_filtered(Host, params[:id])
flash = _("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "Host"), :name => @host.name}
render :update do |page|
page.redirect_to :action => @lastaction, :id => @host.id, :display => session[:host_display], :flash_msg => flash
end
end
when "save"
if session[:host_items].nil?
@host = find_by_id_filtered(Host, params[:id])
old_host_attributes = @host.attributes.clone
valid_host = find_by_id_filtered(Host, params[:id])
set_record_vars(valid_host, :validate) # Set the record variables, but don't save
if valid_record?(valid_host) && set_record_vars(@host) && @host.save
add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "host"), :name => @host.name})
@breadcrumbs.pop if @breadcrumbs
AuditEvent.success(build_saved_audit_hash_angular(old_host_attributes, @host, false))
session[:flash_msgs] = @flash_array.dup # Put msgs in session for next transaction
render :update do |page|
page.redirect_to :action => "show", :id => @host.id.to_s
end
return
else
@errors.each { |msg| add_flash(msg, :error) }
@host.errors.each do |field, msg|
add_flash("#{field.to_s.capitalize} #{msg}", :error)
end
drop_breadcrumb(:name => "Edit Host '#{@host.name}'", :url => "/host/edit/#{@host.id}")
@in_a_form = true
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
else
valid_host = find_by_id_filtered(Host, !params[:validate_id].blank? ?
params[:validate_id] :
session[:host_items].first.to_i)
# Set the record variables, but don't save
settings, creds, verify = set_credentials_record_vars(valid_host, :validate)
if valid_record?(valid_host) && verify
@error = Host.multi_host_update(session[:host_items], settings, creds)
end
if @error || @error.blank?
# redirect_to :action => 'show_list', :flash_msg=>_("Credentials/Settings saved successfully")
render :update do |page|
page.redirect_to :action => 'show_list', :flash_msg => _("Credentials/Settings saved successfully")
end
else
drop_breadcrumb(:name => "Edit Host '#{@host.name}'", :url => "/host/edit/#{@host.id}")
@in_a_form = true
# redirect_to :action => 'edit', :flash_msg=>@error, :flash_error =>true
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
end
when "reset"
params[:edittype] = @edit[:edittype] # remember the edit type
add_flash(_("All changes have been reset"), :warning)
@in_a_form = true
session[:flash_msgs] = @flash_array.dup # Put msgs in session for next transaction
render :update do |page|
page.redirect_to :action => 'edit', :id => @host.id.to_s
end
when "validate"
verify_host = find_by_id_filtered(Host, params[:validate_id] ? params[:validate_id].to_i : params[:id])
if session[:host_items].nil?
set_record_vars(verify_host, :validate)
else
set_credentials_record_vars(verify_host, :validate)
end
@in_a_form = true
@changed = session[:changed]
begin
require 'MiqSshUtil'
verify_host.verify_credentials(params[:type], :remember_host => params.key?(:remember_host))
rescue Net::SSH::HostKeyMismatch => e # Capture the Host key mismatch from the verify
render :update do |page|
new_url = url_for(:action => "update", :button => "validate", :type => params[:type], :remember_host => "true", :escape => false)
page << "if (confirm('The Host SSH key has changed, do you want to accept the new key?')) miqAjax('#{new_url}');"
end
return
rescue StandardError => bang
add_flash("#{bang}", :error)
else
add_flash(_("Credential validation was successful"))
end
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
end
def build_saved_audit_hash_angular(old_attributes, new_record, add)
name = new_record.respond_to?(:name) ? new_record.name : new_record.description
msg = "[#{name}] Record #{add ? "added" : "updated"} ("
event = "#{new_record.class.to_s.downcase}_record_#{add ? "add" : "update"}"
attribute_difference = new_record.attributes.to_a - old_attributes.to_a
attribute_difference = Hash[*attribute_difference.flatten]
difference_messages = []
attribute_difference.each do |key, value|
difference_messages << "#{key} changed to #{value}"
end
msg = msg + difference_messages.join(", ") + ")"
{
:event => event,
:target_id => new_record.id,
:target_class => new_record.class.base_class.name,
:userid => session[:userid],
:message => msg
}
end
# handle buttons pressed on the button bar
def button
@edit = session[:edit] # Restore @edit for adv search box
params[:display] = @display if ["vms", "storages"].include?(@display) # Were we displaying vms/storages
if params[:pressed].starts_with?("vm_") || # Handle buttons from sub-items screen
params[:pressed].starts_with?("miq_template_") ||
params[:pressed].starts_with?("guest_") ||
params[:pressed].starts_with?("storage_")
pfx = pfx_for_vm_button_pressed(params[:pressed])
process_vm_buttons(pfx)
scanstorage if params[:pressed] == "storage_scan"
refreshstorage if params[:pressed] == "storage_refresh"
tag(Storage) if params[:pressed] == "storage_tag"
# Control transferred to another screen, so return
return if ["host_drift", "#{pfx}_compare", "#{pfx}_tag", "#{pfx}_policy_sim",
"#{pfx}_retire", "#{pfx}_protect", "#{pfx}_ownership",
"#{pfx}_reconfigure", "#{pfx}_retire", "#{pfx}_right_size",
"storage_tag"].include?(params[:pressed]) && @flash_array.nil?
unless ["#{pfx}_edit", "#{pfx}_miq_request_new", "#{pfx}_clone", "#{pfx}_migrate", "#{pfx}_publish"].include?(params[:pressed])
@refresh_div = "main_div"
@refresh_partial = "layouts/gtl"
show
end
else # Handle Host buttons
params[:page] = @current_page unless @current_page.nil? # Save current page for list refresh
@refresh_div = "main_div" # Default div for button.rjs to refresh
drift_analysis if params[:pressed] == "common_drift"
redirect_to :action => "new" if params[:pressed] == "new"
deletehosts if params[:pressed] == "host_delete"
comparemiq if params[:pressed] == "host_compare"
refreshhosts if params[:pressed] == "host_refresh"
scanhosts if params[:pressed] == "host_scan"
check_compliance_hosts if params[:pressed] == "host_check_compliance"
analyze_check_compliance_hosts if params[:pressed] == "host_analyze_check_compliance"
tag(Host) if params[:pressed] == "host_tag"
assign_policies(Host) if params[:pressed] == "host_protect"
edit_record if params[:pressed] == "host_edit"
custom_buttons if params[:pressed] == "custom_button"
prov_redirect if params[:pressed] == "host_miq_request_new"
# Handle Host power buttons
if ["host_shutdown", "host_reboot", "host_standby", "host_enter_maint_mode", "host_exit_maint_mode",
"host_start", "host_stop", "host_reset"].include?(params[:pressed])
powerbutton_hosts(params[:pressed].split("_")[1..-1].join("_")) # Handle specific power button
end
perf_chart_chooser if params[:pressed] == "perf_reload"
perf_refresh_data if params[:pressed] == "perf_refresh"
return if ["custom_button"].include?(params[:pressed]) # custom button screen, so return, let custom_buttons method handle everything
return if ["host_tag", "host_compare", "common_drift",
"host_protect", "perf_reload"].include?(params[:pressed]) &&
@flash_array.nil? # Another screen showing, so return
if @flash_array.nil? && !@refresh_partial && !["host_miq_request_new"].include?(params[:pressed]) # if no button handler ran, show not implemented msg
add_flash(_("Button not yet implemented"), :error)
@refresh_partial = "layouts/flash_msg"
@refresh_div = "flash_msg_div"
elsif @flash_array && @lastaction == "show"
@host = @record = identify_record(params[:id])
@refresh_partial = "layouts/flash_msg"
@refresh_div = "flash_msg_div"
end
end
if @lastaction == "show" && ["custom_button", "host_miq_request_new"].include?(params[:pressed])
@host = @record = identify_record(params[:id])
end
if !@flash_array.nil? && params[:pressed] == "host_delete" && @single_delete
render :update do |page|
page.redirect_to :action => 'show_list', :flash_msg => @flash_array[0][:message] # redirect to build the retire screen
end
elsif params[:pressed].ends_with?("_edit") || ["host_miq_request_new", "#{pfx}_miq_request_new",
"#{pfx}_clone", "#{pfx}_migrate",
"#{pfx}_publish"].include?(params[:pressed])
if @flash_array
show_list
replace_gtl_main_div
else
if @redirect_controller
if ["host_miq_request_new", "#{pfx}_clone", "#{pfx}_migrate", "#{pfx}_publish"].include?(params[:pressed])
render :update do |page|
if flash_errors?
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
else
page.redirect_to :controller => @redirect_controller,
:action => @refresh_partial,
:id => @redirect_id,
:prov_type => @prov_type,
:prov_id => @prov_id,
:org_controller => @org_controller,
:escape => false
end
end
else
render :update do |page|
page.redirect_to :controller => @redirect_controller, :action => @refresh_partial, :id => @redirect_id, :org_controller => @org_controller
end
end
else
render :update do |page|
page.redirect_to :action => @refresh_partial, :id => @redirect_id
end
end
end
else
if @refresh_div == "main_div" && @lastaction == "show_list"
replace_gtl_main_div
else
render :update do |page| # Use RJS to update the display
unless @refresh_partial.nil?
if @refresh_div == "flash_msg_div"
page.replace(@refresh_div, :partial => @refresh_partial)
else
if @display == "vms" # If displaying vms, action_url s/b show
page << "miqReinitToolbar('center_tb');"
page.replace_html("main_div", :partial => "layouts/gtl", :locals => {:action_url => "show/#{@host.id}"})
elsif @display == "main"
page.replace_html("main_div", :partial => "main")
else
page.replace_html(@refresh_div, :partial => @refresh_partial)
end
end
end
page.replace_html(@refresh_div, :action => @render_action) unless @render_action.nil?
end
end
end
end
def host_form_fields
assert_privileges("host_edit")
host = find_by_id_filtered(Host, params[:id])
validate_against = session.fetch_path(:edit, :validate_against) &&
params[:button] != "reset" ? session.fetch_path(:edit, :validate_against) : nil
host_hash = {
:name => host.name,
:hostname => host.hostname,
:ipmi_address => host.ipmi_address ? host.ipmi_address : "",
:custom_1 => host.custom_1 ? host.custom_1 : "",
:user_assigned_os => host.user_assigned_os,
:operating_system => !(host.operating_system.nil? || host.operating_system.product_name.nil?),
:mac_address => host.mac_address ? host.mac_address : "",
:default_userid => host.authentication_userid.to_s,
:remote_userid => host.has_authentication_type?(:remote) ? host.authentication_userid(:remote).to_s : "",
:ws_userid => host.has_authentication_type?(:ws) ? host.authentication_userid(:ws).to_s : "",
:ipmi_userid => host.has_authentication_type?(:ipmi) ? host.authentication_userid(:ipmi).to_s : "",
:validate_id => validate_against,
}
render :json => host_hash
end
private ############################
def breadcrumb_name(_model)
title_for_hosts
end
# Build the tree object to display the host network info
def build_network_tree
@tree_vms = [] # Capture all VM ids in the tree
host_node = TreeNodeBuilder.generic_tree_node(
"h_#{@host.id}",
@host.name,
"host.png",
"Host: #{@host.name}",
:expand => true
)
host_node[:children] = add_host_branch if @host.switches.length > 0
@network_tree = [host_node].to_json
session[:tree_name] = "network_tree"
end
def add_host_branch
@host.switches.collect do |s|
switch_node = TreeNodeBuilder.generic_tree_node(
"s_#{s.id}",
s.name,
"switch.png",
"Switch: #{s.name}"
)
switch_node_children = []
switch_node_children.concat(add_guest_devices(s)) if s.guest_devices.length > 0
switch_node_children.concat(add_lans(s)) if s.lans.length > 0
switch_node[:children] = switch_node_children unless switch_node_children.empty?
switch_node
end
end
def add_guest_devices(switch)
switch.guest_devices.collect do |p|
TreeNodeBuilder.generic_tree_node(
"n_#{p.id}",
p.device_name,
"pnic.png",
"Physical NIC: #{p.device_name}"
)
end
end
def add_lans(switch)
switch.lans.collect do |l|
lan_node = TreeNodeBuilder.generic_tree_node(
"l_#{l.id}",
l.name,
"lan.png",
"Port Group: #{l.name}"
)
lan_node[:children] = add_vm_nodes(l) if l.respond_to?("vms_and_templates") &&
l.vms_and_templates.length > 0
lan_node
end
end
def add_vm_nodes(lan)
lan.vms_and_templates.sort_by { |l| l.name.downcase }.collect do |v|
if v.authorized_for_user?(session[:userid])
@tree_vms.push(v) unless @tree_vms.include?(v)
if v.template?
image = v.host ? "template.png" : "template-no-host.png"
else
image = "#{v.current_state.downcase}.png"
end
TreeNodeBuilder.generic_tree_node(
"v-#{v.id}",
v.name,
image,
"VM: #{v.name} (Click to view)"
)
end
end
end
# Build the tree object to display the host storage adapter info
def build_sa_tree
host_node = TreeNodeBuilder.generic_tree_node(
"h_#{@host.id}",
@host.name,
"host.png",
"Host: #{@host.name}",
:expand => true,
:style_class => "cfme-no-cursor-node"
)
host_node[:children] = storage_adapters_node if !@host.hardware.nil? &&
@host.hardware.storage_adapters.length > 0
@sa_tree = [host_node].to_json
session[:tree] = "sa"
session[:tree_name] = "sa_tree"
end
def storage_adapters_node
@host.hardware.storage_adapters.collect do |storage_adapter|
storage_adapter_node = TreeNodeBuilder.generic_tree_node(
"sa_#{storage_adapter.id}",
storage_adapter.device_name,
"sa_#{storage_adapter.controller_type.downcase}.png",
"#{storage_adapter.controller_type} Storage Adapter: #{storage_adapter.device_name}",
:style_class => "cfme-no-cursor-node"
)
storage_adapter_node[:children] =
add_miq_scsi_targets_nodes(storage_adapter) if storage_adapter.miq_scsi_targets.length > 0
storage_adapter_node
end
end
def add_miq_scsi_targets_nodes(storage_adapter)
storage_adapter.miq_scsi_targets.collect do |scsi_target|
name = "SCSI Target #{scsi_target.target}"
name += " (#{scsi_target.iscsi_name})" unless scsi_target.iscsi_name.blank?
target_text = name.blank? ? "[empty]" : name
target_node = TreeNodeBuilder.generic_tree_node(
"t_#{scsi_target.id}",
target_text,
"target_scsi.png",
"Target: #{target_text}",
:style_class => "cfme-no-cursor-node"
)
target_node[:children] = add_miq_scsi_luns_nodes(scsi_target) if scsi_target.miq_scsi_luns.length > 0
target_node
end
end
def add_miq_scsi_luns_nodes(target)
target.miq_scsi_luns.collect do |l|
TreeNodeBuilder.generic_tree_node(
"l_#{l.id}",
l.canonical_name,
"lun.png",
"LUN: #{l.canonical_name}",
:style_class => "cfme-no-cursor-node"
)
end
end
# Validate the host record fields
def valid_record?(host)
valid = true
@errors = []
if !host.authentication_userid.blank? && params[:password] != params[:verify]
@errors.push("Default Password and Verify Password fields do not match")
valid = false
@tabnum = "1"
end
if host.authentication_userid.blank? && (!host.authentication_userid(:remote).blank? || !host.authentication_userid(:ws).blank?)
@errors.push("Default User ID must be entered if a Remote Login or Web Services User ID is entered")
valid = false
@tabnum = "1"
end
if !host.authentication_userid(:remote).blank? && params[:remote_password] != params[:remote_verify]
@errors.push("Remote Login Password and Verify Password fields do not match")
valid = false
@tabnum ||= "2"
end
if !host.authentication_userid(:ws).blank? && params[:ws_password] != params[:ws_verify]
@errors.push("Web Services Password and Verify Password fields do not match")
valid = false
@tabnum ||= "3"
end
if !host.authentication_userid(:ipmi).blank? && params[:ipmi_password] != params[:ipmi_verify]
@errors.push("IPMI Password and Verify Password fields do not match")
valid = false
@tabnum ||= "4"
end
if params[:ws_port] && !(params[:ws_port] =~ /^\d+$/)
@errors.push("Web Services Listen Port must be numeric")
valid = false
end
if params[:log_wrapsize] && (!(params[:log_wrapsize] =~ /^\d+$/) || params[:log_wrapsize].to_i == 0)
@errors.push("Log Wrap Size must be numeric and greater than zero")
valid = false
end
valid
end
# Set record variables to new values
def set_record_vars(host, mode = nil)
host.name = params[:name]
host.hostname = params[:hostname].strip unless params[:hostname].nil?
host.ipmi_address = params[:ipmi_address]
host.mac_address = params[:mac_address]
host.custom_1 = params[:custom_1] unless mode == :validate
host.user_assigned_os = params[:user_assigned_os]
_ = set_credentials(host, mode)
true
end
# Set record variables to new values
def set_credentials_record_vars(host, mode = nil)
settings = {}
settings[:scan_frequency] = params[:scan_frequency]
creds = set_credentials(host, mode)
return settings, creds, true
end
def set_credentials(host, mode)
creds = {}
creds[:default] = {:userid => params[:default_userid],
:password => params[:default_password]} unless params[:default_userid].blank?
creds[:remote] = {:userid => params[:remote_userid],
:password => params[:remote_password]} unless params[:remote_userid].blank?
creds[:ws] = {:userid => params[:ws_userid],
:password => params[:ws_password]} unless params[:ws_userid].blank?
creds[:ipmi] = {:userid => params[:ipmi_userid],
:password => params[:ipmi_password]} unless params[:ipmi_userid].blank?
host.update_authentication(creds, :save => (mode != :validate))
creds
end
# gather up the host records from the DB
def get_hosts
page = params[:page].nil? ? 1 : params[:page].to_i
@current_page = page
@items_per_page = @settings[:perpage][@gtl_type.to_sym] # Get the per page setting for this gtl type
@host_pages, @hosts = paginate(:hosts, :per_page => @items_per_page, :order => @col_names[get_sort_col] + " " + @sortdir)
end
def get_session_data
@title = "Hosts"
@layout = "host"
@drift_db = "Host"
@lastaction = session[:host_lastaction]
@display = session[:host_display]
@filters = session[:host_filters]
@catinfo = session[:host_catinfo]
@base = session[:vm_compare_base]
end
def set_session_data
session[:host_lastaction] = @lastaction
session[:host_display] = @display unless @display.nil?
session[:host_filters] = @filters
session[:host_catinfo] = @catinfo
session[:miq_compressed] = @compressed unless @compressed.nil?
session[:miq_exists_mode] = @exists_mode unless @exists_mode.nil?
session[:vm_compare_base] = @base
end
end
Validate should use the db password if params[:password] is nil
class HostController < ApplicationController
before_action :check_privileges
before_action :get_session_data
after_action :cleanup_action
after_action :set_session_data
def index
redirect_to :action => 'show_list'
end
def show_association(action, display_name, listicon, method, klass, association = nil, conditions = nil)
set_config(identify_record(params[:id]))
super
end
def show
return if perfmenu_click?
@lastaction = "show"
@showtype = "config"
@display = params[:display] || "main" unless control_selected?
@host = @record = identify_record(params[:id])
return if record_no_longer_exists?(@host, 'Host')
@gtl_url = "/host/show/" << @host.id.to_s << "?"
@showtype = "config"
set_config(@host)
case @display
when "download_pdf", "main", "summary_only"
get_tagdata(@host)
drop_breadcrumb({:name => "Hosts", :url => "/host/show_list?page=#{@current_page}&refresh=y"}, true)
drop_breadcrumb(:name => @host.name + " (Summary)", :url => "/host/show/#{@host.id}")
@showtype = "main"
set_summary_pdf_data if ["download_pdf", "summary_only"].include?(@display)
when "devices"
drop_breadcrumb(:name => @host.name + " (Devices)", :url => "/host/show/#{@host.id}?display=devices")
when "os_info"
drop_breadcrumb(:name => @host.name + " (OS Information)", :url => "/host/show/#{@host.id}?display=os_info")
when "hv_info"
drop_breadcrumb(:name => @host.name + " (VM Monitor Information)", :url => "/host/show/#{@host.id}?display=hv_info")
when "network"
drop_breadcrumb(:name => @host.name + " (Network)", :url => "/host/show/#{@host.id}?display=network")
build_network_tree
when "performance"
@showtype = "performance"
drop_breadcrumb(:name => "#{@host.name} Capacity & Utilization", :url => "/host/show/#{@host.id}?display=#{@display}&refresh=n")
perf_gen_init_options # Intialize perf chart options, charts will be generated async
when "timeline"
@showtype = "timeline"
session[:tl_record_id] = params[:id] if params[:id]
@record = find_by_id_filtered(Host, session[:tl_record_id])
@timeline = @timeline_filter = true
@lastaction = "show_timeline"
tl_build_timeline # Create the timeline report
drop_breadcrumb(:name => "Timelines", :url => "/host/show/#{@record.id}?refresh=n&display=timeline")
when "compliance_history"
count = params[:count] ? params[:count].to_i : 10
session[:ch_tree] = compliance_history_tree(@host, count).to_json
session[:tree_name] = "ch_tree"
session[:squash_open] = (count == 1)
drop_breadcrumb({:name => @host.name, :url => "/host/show/#{@host.id}"}, true)
if count == 1
drop_breadcrumb(:name => @host.name + " (Latest Compliance Check)", :url => "/host/show/#{@host.id}?display=#{@display}")
else
drop_breadcrumb(:name => @host.name + " (Compliance History - Last #{count} Checks)", :url => "/host/show/#{@host.id}?display=#{@display}")
end
@showtype = @display
when "storage_adapters"
drop_breadcrumb(:name => @host.name + " (Storage Adapters)", :url => "/host/show/#{@host.id}?display=storage_adapters")
build_sa_tree
when "miq_templates", "vms"
title = @display == "vms" ? "VMs" : "Templates"
kls = @display == "vms" ? Vm : MiqTemplate
drop_breadcrumb(:name => @host.name + " (All #{title})", :url => "/host/show/#{@host.id}?display=#{@display}")
@view, @pages = get_view(kls, :parent => @host) # Get the records (into a view) and the paginator
@showtype = @display
if @view.extras[:total_count] && @view.extras[:auth_count] &&
@view.extras[:total_count] > @view.extras[:auth_count]
@bottom_msg = "* You are not authorized to view " + pluralize(@view.extras[:total_count] - @view.extras[:auth_count], "other #{title.singularize}") + " on this Host"
end
when "cloud_tenants"
drop_breadcrumb(:name => _("%s (All cloud tenants present on this host)") % @host.name,
:url => "/host/show/#{@host.id}?display=cloud_tenants")
@view, @pages = get_view(CloudTenant, :parent => @host) # Get the records (into a view) and the paginator
@showtype = "cloud_tenants"
when "resource_pools"
drop_breadcrumb(:name => @host.name + " (All Resource Pools)", :url => "/host/show/#{@host.id}?display=resource_pools")
@view, @pages = get_view(ResourcePool, :parent => @host) # Get the records (into a view) and the paginator
@showtype = "resource_pools"
when "storages"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "storages")})", :url => "/host/show/#{@host.id}?display=storages")
@view, @pages = get_view(Storage, :parent => @host) # Get the records (into a view) and the paginator
@showtype = "storages"
if @view.extras[:total_count] && @view.extras[:auth_count] &&
@view.extras[:total_count] > @view.extras[:auth_count]
@bottom_msg = "* You are not authorized to view " + pluralize(@view.extras[:total_count] - @view.extras[:auth_count], "other " + ui_lookup(:table => "storages")) + " on this Host"
end
when "ontap_logical_disks"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "ontap_logical_disk")})", :url => "/host/show/#{@host.id}?display=ontap_logicals_disks")
@view, @pages = get_view(OntapLogicalDisk, :parent => @host, :parent_method => :logical_disks) # Get the records (into a view) and the paginator
@showtype = "ontap_logicals_disks"
when "ontap_storage_systems"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "ontap_storage_system")})", :url => "/host/show/#{@host.id}?display=ontap_storage_systems")
@view, @pages = get_view(OntapStorageSystem, :parent => @host, :parent_method => :storage_systems) # Get the records (into a view) and the paginator
@showtype = "ontap_storage_systems"
when "ontap_storage_volumes"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "ontap_storage_volume")})", :url => "/host/show/#{@host.id}?display=ontap_storage_volumes")
@view, @pages = get_view(OntapStorageVolume, :parent => @host, :parent_method => :storage_volumes) # Get the records (into a view) and the paginator
@showtype = "ontap_storage_volumes"
when "ontap_file_shares"
drop_breadcrumb(:name => @host.name + " (All #{ui_lookup(:tables => "ontap_file_share")})", :url => "/host/show/#{@host.id}?display=ontap_file_shares")
@view, @pages = get_view(OntapFileShare, :parent => @host, :parent_method => :file_shares) # Get the records (into a view) and the paginator
@showtype = "ontap_file_shares"
end
@lastaction = "show"
session[:tl_record_id] = @record.id
# Came in from outside show_list partial
if params[:ppsetting] || params[:searchtag] || params[:entry] || params[:sort_choice]
replace_gtl_main_div
end
end
def filesystems_subsets
condition = nil
label = _('Files')
host_service_group = HostServiceGroup.where(:id => params['host_service_group']).first
if host_service_group
condition = host_service_group.host_service_group_filesystems_condition
label = _("Configuration files of %s") % 'nova service'
end
# HACK: UI get_view can't do arel relations, so I need to expose conditions
condition = condition.to_sql if condition
return label, condition
end
def set_config_local
set_config(identify_record(params[:id]))
super
end
alias_method :set_config_local, :drift_history
alias_method :set_config_local, :groups
alias_method :set_config_local, :patches
alias_method :set_config_local, :users
def filesystems
label, condition = filesystems_subsets
show_association('filesystems', label, 'filesystems', :filesystems, Filesystem, nil, condition)
end
def host_services_subsets
condition = nil
label = _('Services')
host_service_group = HostServiceGroup.where(:id => params['host_service_group']).first
if host_service_group
case params[:status]
when 'running'
condition = host_service_group.running_system_services_condition
label = _("Running system services of %s") % host_service_group.name
when 'failed'
condition = host_service_group.failed_system_services_condition
label = _("Failed system services of %s") % host_service_group.name
when 'all'
condition = nil
label = _("All system services of %s") % host_service_group.name
end
if condition
# Amend the condition with the openstack host service foreign key
condition = condition.and(host_service_group.host_service_group_system_services_condition)
else
condition = host_service_group.host_service_group_system_services_condition
end
end
# HACK: UI get_view can't do arel relations, so I need to expose conditions
condition = condition.to_sql if condition
return label, condition
end
def host_services
label, condition = host_services_subsets
show_association('host_services', label, 'service', :host_services, SystemService, nil, condition)
end
def advanced_settings
show_association('advanced_settings', 'Advanced Settings', 'advancedsetting', :advanced_settings, AdvancedSetting)
end
def firewall_rules
@display = "main"
show_association('firewall_rules', 'Firewall Rules', 'firewallrule', :firewall_rules, FirewallRule)
end
def guest_applications
show_association('guest_applications', 'Packages', 'guest_application', :guest_applications, GuestApplication)
end
def toggle_policy_profile
if session[:policy_assignment_compressed].nil?
session[:policy_assignment_compressed] = false
else
session[:policy_assignment_compressed] = !session[:policy_assignment_compressed]
end
@compressed = session[:policy_assignment_compressed]
protect_build_screen
protect_set_db_record
render :update do |page| # Use RJS to update the display
page.replace_html("view_buttons_div", :partial => "layouts/view_buttons") # Replace the view buttons
page.replace_html("main_div", :partial => "layouts/protecting") # Replace the main div area contents
end
end
# Show the main Host list view
def show_list
session[:host_items] = nil
process_show_list
end
def start
redirect_to :action => 'show_list'
end
def new
assert_privileges("host_new")
@host = Host.new
@in_a_form = true
drop_breadcrumb(:name => "Add New Host", :url => "/host/new")
end
def create
assert_privileges("host_new")
case params[:button]
when "cancel"
render :update do |page|
page.redirect_to :action => 'show_list', :flash_msg => _("Add of new %s was cancelled by the user") % ui_lookup(:model => "Host")
end
when "add"
@host = Host.new
old_host_attributes = @host.attributes.clone
set_record_vars(@host, :validate) # Set the record variables, but don't save
@host.vmm_vendor = "unknown"
if valid_record?(@host) && @host.save
set_record_vars(@host) # Save the authentication records for this host
AuditEvent.success(build_saved_audit_hash_angular(old_host_attributes, @host, params[:button] == "add"))
message = _("%{model} \"%{name}\" was added") % {:model => ui_lookup(:model => "Host"), :name => @host.name}
render :update do |page|
page.redirect_to :action => 'show_list',
:flash_msg => message
end
else
@in_a_form = true
@errors.each { |msg| add_flash(msg, :error) }
@host.errors.each do |field, msg|
add_flash("#{field.to_s.capitalize} #{msg}", :error)
end
drop_breadcrumb(:name => "Add New Host", :url => "/host/new")
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
when "validate"
verify_host = Host.new
set_record_vars(verify_host, :validate)
@in_a_form = true
begin
verify_host.verify_credentials(params[:type])
rescue StandardError => bang
add_flash("#{bang}", :error)
else
add_flash(_("Credential validation was successful"))
end
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
end
def edit
assert_privileges("host_edit")
if session[:host_items].nil?
@host = find_by_id_filtered(Host, params[:id])
@in_a_form = true
session[:changed] = false
drop_breadcrumb(:name => "Edit Host '#{@host.name}'", :url => "/host/edit/#{@host.id}")
@title = "Info/Settings"
else # if editing credentials for multi host
@title = "Credentials/Settings"
if params[:selected_host]
@host = find_by_id_filtered(Host, params[:selected_host])
else
@host = Host.new
end
@changed = true
@showlinks = true
@in_a_form = true
# Get the db records that are being tagged
hostitems = Host.find(session[:host_items]).sort { |a, b| a.name <=> b.name }
@selected_hosts = {}
hostitems.each do |h|
@selected_hosts[h.id] = h.name
end
build_targets_hash(hostitems)
@view = get_db_view(Host) # Instantiate the MIQ Report view object
@view.table = MiqFilter.records2table(hostitems, :only => @view.cols + ['id'])
end
end
def update
assert_privileges("host_edit")
case params[:button]
when "cancel"
session[:edit] = nil # clean out the saved info
flash = "Edit for Host \""
@breadcrumbs.pop if @breadcrumbs
if !session[:host_items].nil?
flash = _("Edit of credentials for selected %s was cancelled by the user") % ui_lookup(:models => "Host")
# redirect_to :action => @lastaction, :display=>session[:host_display], :flash_msg=>flash
render :update do |page|
page.redirect_to :action => @lastaction, :display => session[:host_display], :flash_msg => flash
end
else
@host = find_by_id_filtered(Host, params[:id])
flash = _("Edit of %{model} \"%{name}\" was cancelled by the user") % {:model => ui_lookup(:model => "Host"), :name => @host.name}
render :update do |page|
page.redirect_to :action => @lastaction, :id => @host.id, :display => session[:host_display], :flash_msg => flash
end
end
when "save"
if session[:host_items].nil?
@host = find_by_id_filtered(Host, params[:id])
old_host_attributes = @host.attributes.clone
valid_host = find_by_id_filtered(Host, params[:id])
set_record_vars(valid_host, :validate) # Set the record variables, but don't save
if valid_record?(valid_host) && set_record_vars(@host) && @host.save
add_flash(_("%{model} \"%{name}\" was saved") % {:model => ui_lookup(:model => "host"), :name => @host.name})
@breadcrumbs.pop if @breadcrumbs
AuditEvent.success(build_saved_audit_hash_angular(old_host_attributes, @host, false))
session[:flash_msgs] = @flash_array.dup # Put msgs in session for next transaction
render :update do |page|
page.redirect_to :action => "show", :id => @host.id.to_s
end
return
else
@errors.each { |msg| add_flash(msg, :error) }
@host.errors.each do |field, msg|
add_flash("#{field.to_s.capitalize} #{msg}", :error)
end
drop_breadcrumb(:name => "Edit Host '#{@host.name}'", :url => "/host/edit/#{@host.id}")
@in_a_form = true
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
else
valid_host = find_by_id_filtered(Host, !params[:validate_id].blank? ?
params[:validate_id] :
session[:host_items].first.to_i)
# Set the record variables, but don't save
settings, creds, verify = set_credentials_record_vars(valid_host, :validate)
if valid_record?(valid_host) && verify
@error = Host.multi_host_update(session[:host_items], settings, creds)
end
if @error || @error.blank?
# redirect_to :action => 'show_list', :flash_msg=>_("Credentials/Settings saved successfully")
render :update do |page|
page.redirect_to :action => 'show_list', :flash_msg => _("Credentials/Settings saved successfully")
end
else
drop_breadcrumb(:name => "Edit Host '#{@host.name}'", :url => "/host/edit/#{@host.id}")
@in_a_form = true
# redirect_to :action => 'edit', :flash_msg=>@error, :flash_error =>true
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
end
when "reset"
params[:edittype] = @edit[:edittype] # remember the edit type
add_flash(_("All changes have been reset"), :warning)
@in_a_form = true
session[:flash_msgs] = @flash_array.dup # Put msgs in session for next transaction
render :update do |page|
page.redirect_to :action => 'edit', :id => @host.id.to_s
end
when "validate"
verify_host = find_by_id_filtered(Host, params[:validate_id] ? params[:validate_id].to_i : params[:id])
if session[:host_items].nil?
set_record_vars(verify_host, :validate)
else
set_credentials_record_vars(verify_host, :validate)
end
@in_a_form = true
@changed = session[:changed]
begin
require 'MiqSshUtil'
verify_host.verify_credentials(params[:type], :remember_host => params.key?(:remember_host))
rescue Net::SSH::HostKeyMismatch => e # Capture the Host key mismatch from the verify
render :update do |page|
new_url = url_for(:action => "update", :button => "validate", :type => params[:type], :remember_host => "true", :escape => false)
page << "if (confirm('The Host SSH key has changed, do you want to accept the new key?')) miqAjax('#{new_url}');"
end
return
rescue StandardError => bang
add_flash("#{bang}", :error)
else
add_flash(_("Credential validation was successful"))
end
render :update do |page|
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
end
end
end
def build_saved_audit_hash_angular(old_attributes, new_record, add)
name = new_record.respond_to?(:name) ? new_record.name : new_record.description
msg = "[#{name}] Record #{add ? "added" : "updated"} ("
event = "#{new_record.class.to_s.downcase}_record_#{add ? "add" : "update"}"
attribute_difference = new_record.attributes.to_a - old_attributes.to_a
attribute_difference = Hash[*attribute_difference.flatten]
difference_messages = []
attribute_difference.each do |key, value|
difference_messages << "#{key} changed to #{value}"
end
msg = msg + difference_messages.join(", ") + ")"
{
:event => event,
:target_id => new_record.id,
:target_class => new_record.class.base_class.name,
:userid => session[:userid],
:message => msg
}
end
# handle buttons pressed on the button bar
def button
@edit = session[:edit] # Restore @edit for adv search box
params[:display] = @display if ["vms", "storages"].include?(@display) # Were we displaying vms/storages
if params[:pressed].starts_with?("vm_") || # Handle buttons from sub-items screen
params[:pressed].starts_with?("miq_template_") ||
params[:pressed].starts_with?("guest_") ||
params[:pressed].starts_with?("storage_")
pfx = pfx_for_vm_button_pressed(params[:pressed])
process_vm_buttons(pfx)
scanstorage if params[:pressed] == "storage_scan"
refreshstorage if params[:pressed] == "storage_refresh"
tag(Storage) if params[:pressed] == "storage_tag"
# Control transferred to another screen, so return
return if ["host_drift", "#{pfx}_compare", "#{pfx}_tag", "#{pfx}_policy_sim",
"#{pfx}_retire", "#{pfx}_protect", "#{pfx}_ownership",
"#{pfx}_reconfigure", "#{pfx}_retire", "#{pfx}_right_size",
"storage_tag"].include?(params[:pressed]) && @flash_array.nil?
unless ["#{pfx}_edit", "#{pfx}_miq_request_new", "#{pfx}_clone", "#{pfx}_migrate", "#{pfx}_publish"].include?(params[:pressed])
@refresh_div = "main_div"
@refresh_partial = "layouts/gtl"
show
end
else # Handle Host buttons
params[:page] = @current_page unless @current_page.nil? # Save current page for list refresh
@refresh_div = "main_div" # Default div for button.rjs to refresh
drift_analysis if params[:pressed] == "common_drift"
redirect_to :action => "new" if params[:pressed] == "new"
deletehosts if params[:pressed] == "host_delete"
comparemiq if params[:pressed] == "host_compare"
refreshhosts if params[:pressed] == "host_refresh"
scanhosts if params[:pressed] == "host_scan"
check_compliance_hosts if params[:pressed] == "host_check_compliance"
analyze_check_compliance_hosts if params[:pressed] == "host_analyze_check_compliance"
tag(Host) if params[:pressed] == "host_tag"
assign_policies(Host) if params[:pressed] == "host_protect"
edit_record if params[:pressed] == "host_edit"
custom_buttons if params[:pressed] == "custom_button"
prov_redirect if params[:pressed] == "host_miq_request_new"
# Handle Host power buttons
if ["host_shutdown", "host_reboot", "host_standby", "host_enter_maint_mode", "host_exit_maint_mode",
"host_start", "host_stop", "host_reset"].include?(params[:pressed])
powerbutton_hosts(params[:pressed].split("_")[1..-1].join("_")) # Handle specific power button
end
perf_chart_chooser if params[:pressed] == "perf_reload"
perf_refresh_data if params[:pressed] == "perf_refresh"
return if ["custom_button"].include?(params[:pressed]) # custom button screen, so return, let custom_buttons method handle everything
return if ["host_tag", "host_compare", "common_drift",
"host_protect", "perf_reload"].include?(params[:pressed]) &&
@flash_array.nil? # Another screen showing, so return
if @flash_array.nil? && !@refresh_partial && !["host_miq_request_new"].include?(params[:pressed]) # if no button handler ran, show not implemented msg
add_flash(_("Button not yet implemented"), :error)
@refresh_partial = "layouts/flash_msg"
@refresh_div = "flash_msg_div"
elsif @flash_array && @lastaction == "show"
@host = @record = identify_record(params[:id])
@refresh_partial = "layouts/flash_msg"
@refresh_div = "flash_msg_div"
end
end
if @lastaction == "show" && ["custom_button", "host_miq_request_new"].include?(params[:pressed])
@host = @record = identify_record(params[:id])
end
if !@flash_array.nil? && params[:pressed] == "host_delete" && @single_delete
render :update do |page|
page.redirect_to :action => 'show_list', :flash_msg => @flash_array[0][:message] # redirect to build the retire screen
end
elsif params[:pressed].ends_with?("_edit") || ["host_miq_request_new", "#{pfx}_miq_request_new",
"#{pfx}_clone", "#{pfx}_migrate",
"#{pfx}_publish"].include?(params[:pressed])
if @flash_array
show_list
replace_gtl_main_div
else
if @redirect_controller
if ["host_miq_request_new", "#{pfx}_clone", "#{pfx}_migrate", "#{pfx}_publish"].include?(params[:pressed])
render :update do |page|
if flash_errors?
page.replace("flash_msg_div", :partial => "layouts/flash_msg")
else
page.redirect_to :controller => @redirect_controller,
:action => @refresh_partial,
:id => @redirect_id,
:prov_type => @prov_type,
:prov_id => @prov_id,
:org_controller => @org_controller,
:escape => false
end
end
else
render :update do |page|
page.redirect_to :controller => @redirect_controller, :action => @refresh_partial, :id => @redirect_id, :org_controller => @org_controller
end
end
else
render :update do |page|
page.redirect_to :action => @refresh_partial, :id => @redirect_id
end
end
end
else
if @refresh_div == "main_div" && @lastaction == "show_list"
replace_gtl_main_div
else
render :update do |page| # Use RJS to update the display
unless @refresh_partial.nil?
if @refresh_div == "flash_msg_div"
page.replace(@refresh_div, :partial => @refresh_partial)
else
if @display == "vms" # If displaying vms, action_url s/b show
page << "miqReinitToolbar('center_tb');"
page.replace_html("main_div", :partial => "layouts/gtl", :locals => {:action_url => "show/#{@host.id}"})
elsif @display == "main"
page.replace_html("main_div", :partial => "main")
else
page.replace_html(@refresh_div, :partial => @refresh_partial)
end
end
end
page.replace_html(@refresh_div, :action => @render_action) unless @render_action.nil?
end
end
end
end
def host_form_fields
assert_privileges("host_edit")
host = find_by_id_filtered(Host, params[:id])
validate_against = session.fetch_path(:edit, :validate_against) &&
params[:button] != "reset" ? session.fetch_path(:edit, :validate_against) : nil
host_hash = {
:name => host.name,
:hostname => host.hostname,
:ipmi_address => host.ipmi_address ? host.ipmi_address : "",
:custom_1 => host.custom_1 ? host.custom_1 : "",
:user_assigned_os => host.user_assigned_os,
:operating_system => !(host.operating_system.nil? || host.operating_system.product_name.nil?),
:mac_address => host.mac_address ? host.mac_address : "",
:default_userid => host.authentication_userid.to_s,
:remote_userid => host.has_authentication_type?(:remote) ? host.authentication_userid(:remote).to_s : "",
:ws_userid => host.has_authentication_type?(:ws) ? host.authentication_userid(:ws).to_s : "",
:ipmi_userid => host.has_authentication_type?(:ipmi) ? host.authentication_userid(:ipmi).to_s : "",
:validate_id => validate_against,
}
render :json => host_hash
end
private ############################
def breadcrumb_name(_model)
title_for_hosts
end
# Build the tree object to display the host network info
def build_network_tree
@tree_vms = [] # Capture all VM ids in the tree
host_node = TreeNodeBuilder.generic_tree_node(
"h_#{@host.id}",
@host.name,
"host.png",
"Host: #{@host.name}",
:expand => true
)
host_node[:children] = add_host_branch if @host.switches.length > 0
@network_tree = [host_node].to_json
session[:tree_name] = "network_tree"
end
def add_host_branch
@host.switches.collect do |s|
switch_node = TreeNodeBuilder.generic_tree_node(
"s_#{s.id}",
s.name,
"switch.png",
"Switch: #{s.name}"
)
switch_node_children = []
switch_node_children.concat(add_guest_devices(s)) if s.guest_devices.length > 0
switch_node_children.concat(add_lans(s)) if s.lans.length > 0
switch_node[:children] = switch_node_children unless switch_node_children.empty?
switch_node
end
end
def add_guest_devices(switch)
switch.guest_devices.collect do |p|
TreeNodeBuilder.generic_tree_node(
"n_#{p.id}",
p.device_name,
"pnic.png",
"Physical NIC: #{p.device_name}"
)
end
end
def add_lans(switch)
switch.lans.collect do |l|
lan_node = TreeNodeBuilder.generic_tree_node(
"l_#{l.id}",
l.name,
"lan.png",
"Port Group: #{l.name}"
)
lan_node[:children] = add_vm_nodes(l) if l.respond_to?("vms_and_templates") &&
l.vms_and_templates.length > 0
lan_node
end
end
def add_vm_nodes(lan)
lan.vms_and_templates.sort_by { |l| l.name.downcase }.collect do |v|
if v.authorized_for_user?(session[:userid])
@tree_vms.push(v) unless @tree_vms.include?(v)
if v.template?
image = v.host ? "template.png" : "template-no-host.png"
else
image = "#{v.current_state.downcase}.png"
end
TreeNodeBuilder.generic_tree_node(
"v-#{v.id}",
v.name,
image,
"VM: #{v.name} (Click to view)"
)
end
end
end
# Build the tree object to display the host storage adapter info
def build_sa_tree
host_node = TreeNodeBuilder.generic_tree_node(
"h_#{@host.id}",
@host.name,
"host.png",
"Host: #{@host.name}",
:expand => true,
:style_class => "cfme-no-cursor-node"
)
host_node[:children] = storage_adapters_node if !@host.hardware.nil? &&
@host.hardware.storage_adapters.length > 0
@sa_tree = [host_node].to_json
session[:tree] = "sa"
session[:tree_name] = "sa_tree"
end
def storage_adapters_node
@host.hardware.storage_adapters.collect do |storage_adapter|
storage_adapter_node = TreeNodeBuilder.generic_tree_node(
"sa_#{storage_adapter.id}",
storage_adapter.device_name,
"sa_#{storage_adapter.controller_type.downcase}.png",
"#{storage_adapter.controller_type} Storage Adapter: #{storage_adapter.device_name}",
:style_class => "cfme-no-cursor-node"
)
storage_adapter_node[:children] =
add_miq_scsi_targets_nodes(storage_adapter) if storage_adapter.miq_scsi_targets.length > 0
storage_adapter_node
end
end
def add_miq_scsi_targets_nodes(storage_adapter)
storage_adapter.miq_scsi_targets.collect do |scsi_target|
name = "SCSI Target #{scsi_target.target}"
name += " (#{scsi_target.iscsi_name})" unless scsi_target.iscsi_name.blank?
target_text = name.blank? ? "[empty]" : name
target_node = TreeNodeBuilder.generic_tree_node(
"t_#{scsi_target.id}",
target_text,
"target_scsi.png",
"Target: #{target_text}",
:style_class => "cfme-no-cursor-node"
)
target_node[:children] = add_miq_scsi_luns_nodes(scsi_target) if scsi_target.miq_scsi_luns.length > 0
target_node
end
end
def add_miq_scsi_luns_nodes(target)
target.miq_scsi_luns.collect do |l|
TreeNodeBuilder.generic_tree_node(
"l_#{l.id}",
l.canonical_name,
"lun.png",
"LUN: #{l.canonical_name}",
:style_class => "cfme-no-cursor-node"
)
end
end
# Validate the host record fields
def valid_record?(host)
valid = true
@errors = []
if !host.authentication_userid.blank? && params[:password] != params[:verify]
@errors.push("Default Password and Verify Password fields do not match")
valid = false
@tabnum = "1"
end
if host.authentication_userid.blank? && (!host.authentication_userid(:remote).blank? || !host.authentication_userid(:ws).blank?)
@errors.push("Default User ID must be entered if a Remote Login or Web Services User ID is entered")
valid = false
@tabnum = "1"
end
if !host.authentication_userid(:remote).blank? && params[:remote_password] != params[:remote_verify]
@errors.push("Remote Login Password and Verify Password fields do not match")
valid = false
@tabnum ||= "2"
end
if !host.authentication_userid(:ws).blank? && params[:ws_password] != params[:ws_verify]
@errors.push("Web Services Password and Verify Password fields do not match")
valid = false
@tabnum ||= "3"
end
if !host.authentication_userid(:ipmi).blank? && params[:ipmi_password] != params[:ipmi_verify]
@errors.push("IPMI Password and Verify Password fields do not match")
valid = false
@tabnum ||= "4"
end
if params[:ws_port] && !(params[:ws_port] =~ /^\d+$/)
@errors.push("Web Services Listen Port must be numeric")
valid = false
end
if params[:log_wrapsize] && (!(params[:log_wrapsize] =~ /^\d+$/) || params[:log_wrapsize].to_i == 0)
@errors.push("Log Wrap Size must be numeric and greater than zero")
valid = false
end
valid
end
# Set record variables to new values
def set_record_vars(host, mode = nil)
host.name = params[:name]
host.hostname = params[:hostname].strip unless params[:hostname].nil?
host.ipmi_address = params[:ipmi_address]
host.mac_address = params[:mac_address]
host.custom_1 = params[:custom_1] unless mode == :validate
host.user_assigned_os = params[:user_assigned_os]
_ = set_credentials(host, mode)
true
end
# Set record variables to new values
def set_credentials_record_vars(host, mode = nil)
settings = {}
settings[:scan_frequency] = params[:scan_frequency]
creds = set_credentials(host, mode)
return settings, creds, true
end
def set_credentials(host, mode)
creds = {}
default_password = params[:default_password] ? params[:default_password] : host.authentication_password
remote_password = params[:remote_password] ? params[:remote_password] : host.authentication_password(:remote)
ws_password = params[:ws_password] ? params[:ws_password] : host.authentication_password(:ws)
ipmi_password = params[:ipmi_password] ? params[:ipmi_password] : host.authentication_password(:ipmi)
creds[:default] = {:userid => params[:default_userid],
:password => default_password} unless params[:default_userid].blank?
creds[:remote] = {:userid => params[:remote_userid],
:password => remote_password} unless params[:remote_userid].blank?
creds[:ws] = {:userid => params[:ws_userid],
:password => ws_password} unless params[:ws_userid].blank?
creds[:ipmi] = {:userid => params[:ipmi_userid],
:password => ipmi_password} unless params[:ipmi_userid].blank?
host.update_authentication(creds, :save => (mode != :validate))
creds
end
# gather up the host records from the DB
def get_hosts
page = params[:page].nil? ? 1 : params[:page].to_i
@current_page = page
@items_per_page = @settings[:perpage][@gtl_type.to_sym] # Get the per page setting for this gtl type
@host_pages, @hosts = paginate(:hosts, :per_page => @items_per_page, :order => @col_names[get_sort_col] + " " + @sortdir)
end
def get_session_data
@title = "Hosts"
@layout = "host"
@drift_db = "Host"
@lastaction = session[:host_lastaction]
@display = session[:host_display]
@filters = session[:host_filters]
@catinfo = session[:host_catinfo]
@base = session[:vm_compare_base]
end
def set_session_data
session[:host_lastaction] = @lastaction
session[:host_display] = @display unless @display.nil?
session[:host_filters] = @filters
session[:host_catinfo] = @catinfo
session[:miq_compressed] = @compressed unless @compressed.nil?
session[:miq_exists_mode] = @exists_mode unless @exists_mode.nil?
session[:vm_compare_base] = @base
end
end
|
class JobsController < ApplicationController
before_action :set_job, only: [:show, :edit, :update, :destroy, :execute]
# GET /jobs
def index
@jobs = Job.all
@paginated_jobs = @jobs.paginate(:page => params[:page], :per_page => Settings.Pagination.NoOfEntriesPerPage)
end
# GET /jobs/1
def show
@tasks = Task.where(:job => @job)
end
# GET /jobs/new
def new
@job = Job.new
end
# GET /jobs/1/edit
def edit
end
def create_combo
list = JSON.parse params[:list]
packages = list["packages"]
task_state_pending = TaskState.where(name: "Pending")[0]
cpv_state_queued = ConcretePackageState.where(name: "Queued for Installation")[0]
#TODO: extract code, see create and create_multiple!
if current_user
@job = Job.new(user: current_user,
started_at: Time.new,
is_in_preview: true)
end
systems = []
cpvs = []
packages.each do |pkg|
if pkg["pristine"] == true
if Package.find( pkg["id"] )
Package.find( pkg["id"] ).get_available_cpvs.each do |cpv|
cpvs << cpv
end
end
else
pkg["cpvs"].each do |cpv|
if ConcretePackageVersion.find( cpv["id"] )
cpvs << ConcretePackageVersion.find( cpv["id"] )
end
end
end
cpvs.each do |cpv|
systems << cpv.system
end
end
systems = systems.uniq
systems.each do |sys|
@task = Task.new(
task_state: task_state_pending,
tries: 0 )
cpvs.each do |cpv|
if cpv.system == sys
@task.concrete_package_versions << cpv
cpv.concrete_package_state = cpv_state_queued
cpv.save()
end
end
@task.save
@job.tasks << @task
end
@job.save
render text: job_path( @job )
end
def create_multiple
systems = []
task_state_pending = TaskState.where(name: "Pending")[0]
cpv_state_queued = ConcretePackageState.where(name: "Queued for Installation")[0]
if params[:all]
# get all systems with available updates
System.all.reject{ |s| s.get_installable_CPVs.count < 1 }.each do |sys|
systems << sys
end
else
# get system IDs from submitted array
if params[:systems]
params[:systems].each do |sysID|
systems << System.find( sysID )
end
end
end
if current_user
@job = Job.new(user: current_user,
started_at: Time.new,
is_in_preview: true)
end
# create a task for each system:
systems.each do |sys|
@task = Task.new(
task_state: task_state_pending,
tries: 0 )
@task.concrete_package_versions << sys.get_installable_CPVs
@task.concrete_package_versions.each do |update|
update.concrete_package_state = cpv_state_queued
update.save()
end
@task.save
@job.tasks << @task
end
@job.save
redirect_to @job
end
# POST /jobs
def create
@task = Task.new(
task_state: TaskState.where(name: "Pending")[0],
tries: 0 )
if params[:all]
# get task IDs from system, map to strings
@task.concrete_package_versions << System.find(params[:system_id]).concrete_package_versions.where(concrete_package_state: ConcretePackageState.first ) #TODO: centralised state manager
else
# get task IDs from submitted array
if params[:updates]
params[:updates].each do |updateID|
@task.concrete_package_versions << ConcretePackageVersion.find( updateID )
end
end
end
if ( ConcretePackageState.exists?(name: "Queued for Installation") )
cpv_state_queued = ConcretePackageState.where(name: "Queued for Installation")[0]
@task.concrete_package_versions.each do |update|
update.concrete_package_state = cpv_state_queued
update.save()
end
end
@task.save
if current_user
@job = Job.new(user: current_user,
started_at: Time.new,
is_in_preview: true)
@job.tasks << @task
@job.save
redirect_to @job
else
#TODO: log!
end
end
# PATCH/PUT /jobs/1
# PATCH/PUT /jobs/1.json
def update
respond_to do |format|
if @job.update(job_params)
format.html { redirect_to @job, success: 'Job was successfully updated.' }
format.json { render :show, status: :ok, location: @job }
else
format.html { render :edit }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
# DELETE /jobs/1
# DELETE /jobs/1.json
def destroy
@job.destroy
respond_to do |format|
format.html { redirect_to jobs_url, success: 'Job was successfully destroyed.' }
format.json { head :no_content }
end
end
def execute
if params[:execute]
@job.is_in_preview = false
@job.save()
@job.tasks.each do |t|
BackgroundSender.perform_async( t )
end
redirect_to @job
elsif params[:cancel]
stateAvail = ConcretePackageState.where(name: "Available")[0]
@job.tasks.each do |t|
t.concrete_package_versions.each do |cpv|
cpv.concrete_package_state = stateAvail
cpv.task = nil
cpv.save()
end
t.destroy
end
@job.destroy
redirect_to root_path, success: 'Job was successfully cancelled.'
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_job
@job = Job.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def job_params
params.require(:job).permit(:started_at, :user_id)
end
end
message on task execution
class JobsController < ApplicationController
before_action :set_job, only: [:show, :edit, :update, :destroy, :execute]
# GET /jobs
def index
@jobs = Job.all
@paginated_jobs = @jobs.paginate(:page => params[:page], :per_page => Settings.Pagination.NoOfEntriesPerPage)
end
# GET /jobs/1
def show
@tasks = Task.where(:job => @job)
end
# GET /jobs/new
def new
@job = Job.new
end
# GET /jobs/1/edit
def edit
end
def create_combo
list = JSON.parse params[:list]
packages = list["packages"]
task_state_pending = TaskState.where(name: "Pending")[0]
cpv_state_queued = ConcretePackageState.where(name: "Queued for Installation")[0]
#TODO: extract code, see create and create_multiple!
if current_user
@job = Job.new(user: current_user,
started_at: Time.new,
is_in_preview: true)
end
systems = []
cpvs = []
packages.each do |pkg|
if pkg["pristine"] == true
if Package.find( pkg["id"] )
Package.find( pkg["id"] ).get_available_cpvs.each do |cpv|
cpvs << cpv
end
end
else
pkg["cpvs"].each do |cpv|
if ConcretePackageVersion.find( cpv["id"] )
cpvs << ConcretePackageVersion.find( cpv["id"] )
end
end
end
cpvs.each do |cpv|
systems << cpv.system
end
end
systems = systems.uniq
systems.each do |sys|
@task = Task.new(
task_state: task_state_pending,
tries: 0 )
cpvs.each do |cpv|
if cpv.system == sys
@task.concrete_package_versions << cpv
cpv.concrete_package_state = cpv_state_queued
cpv.save()
end
end
@task.save
@job.tasks << @task
end
@job.save
render text: job_path( @job )
end
def create_multiple
systems = []
task_state_pending = TaskState.where(name: "Pending")[0]
cpv_state_queued = ConcretePackageState.where(name: "Queued for Installation")[0]
if params[:all]
# get all systems with available updates
System.all.reject{ |s| s.get_installable_CPVs.count < 1 }.each do |sys|
systems << sys
end
else
# get system IDs from submitted array
if params[:systems]
params[:systems].each do |sysID|
systems << System.find( sysID )
end
end
end
if current_user
@job = Job.new(user: current_user,
started_at: Time.new,
is_in_preview: true)
end
# create a task for each system:
systems.each do |sys|
@task = Task.new(
task_state: task_state_pending,
tries: 0 )
@task.concrete_package_versions << sys.get_installable_CPVs
@task.concrete_package_versions.each do |update|
update.concrete_package_state = cpv_state_queued
update.save()
end
@task.save
@job.tasks << @task
end
@job.save
redirect_to @job
end
# POST /jobs
def create
@task = Task.new(
task_state: TaskState.where(name: "Pending")[0],
tries: 0 )
if params[:all]
# get task IDs from system, map to strings
@task.concrete_package_versions << System.find(params[:system_id]).concrete_package_versions.where(concrete_package_state: ConcretePackageState.first ) #TODO: centralised state manager
else
# get task IDs from submitted array
if params[:updates]
params[:updates].each do |updateID|
@task.concrete_package_versions << ConcretePackageVersion.find( updateID )
end
end
end
if ( ConcretePackageState.exists?(name: "Queued for Installation") )
cpv_state_queued = ConcretePackageState.where(name: "Queued for Installation")[0]
@task.concrete_package_versions.each do |update|
update.concrete_package_state = cpv_state_queued
update.save()
end
end
@task.save
if current_user
@job = Job.new(user: current_user,
started_at: Time.new,
is_in_preview: true)
@job.tasks << @task
@job.save
redirect_to @job
else
#TODO: log!
end
end
# PATCH/PUT /jobs/1
# PATCH/PUT /jobs/1.json
def update
respond_to do |format|
if @job.update(job_params)
format.html { redirect_to @job, success: 'Job was successfully updated.' }
format.json { render :show, status: :ok, location: @job }
else
format.html { render :edit }
format.json { render json: @job.errors, status: :unprocessable_entity }
end
end
end
# DELETE /jobs/1
# DELETE /jobs/1.json
def destroy
@job.destroy
respond_to do |format|
format.html { redirect_to jobs_url, success: 'Job was successfully destroyed.' }
format.json { head :no_content }
end
end
def execute
if params[:execute]
@job.is_in_preview = false
@job.save()
@job.tasks.each do |t|
BackgroundSender.perform_async( t )
end
redirect_to @job, success: 'Job was successfully sent!'
elsif params[:cancel]
stateAvail = ConcretePackageState.where(name: "Available")[0]
@job.tasks.each do |t|
t.concrete_package_versions.each do |cpv|
cpv.concrete_package_state = stateAvail
cpv.task = nil
cpv.save()
end
t.destroy
end
@job.destroy
redirect_to root_path, success: 'Job was successfully cancelled.'
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_job
@job = Job.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def job_params
params.require(:job).permit(:started_at, :user_id)
end
end
|
class JoinController < ApplicationController
# When the user is not yet signed up, we get their project information from
# them first. We store all this in a "guest" user, and then at the end, we
# sign the guest user in, and update the information with their real info. The
# reason we go this way, instead of storing the information in a session, is
# that it works just fine this way, and changing it is a hassle. In
# particular, if we change it, we have to find a way for the front/back end to
# pass information around, which is a bit of a refactoring away from working
# well.
def all
@url = Github.authorization_url join_url
code = params[:code]
access_token = current_or_guest_user.github_access_token
state = starting_state(code, access_token)
session[:state] = state
@step, @substep = step_for_state(state)
start_job(state, params)
@user = current_or_guest_user # the body3_1 form will need access to this user.
end
def dynamic
state = session[:state]
fetcher = session[:fetcher]
if fetcher then
ready = Backend.worker_done? fetcher
if ready then
@result = Backend.wait_for_worker fetcher
session[:fetcher] = nil
end
end
# Just move through the states
if session[:next] then
ready = true
session[:next] = false
end
if ready then
state = next_state(state)
session[:state] = state
step, substep = step_for_state(state)
start_job(state, params)
body = render_to_string :partial => "body#{step}_#{substep}"
explanation = render_to_string :partial => "explanation#{step}"
end
keep_polling = (not ready.nil?)
packet = {
:step => step,
:substep => substep,
:ready => ready,
:keep_polling => keep_polling,
:state => state,
:body => body,
:explanation => explanation,
}.to_json
render :json => packet
end
def start_job(state, params)
# TODO: refactor this duplication
code = params[:code]
access_token = current_or_guest_user.github_access_token
# Start whatever job the state requires
case state
when :start
# TODO: put this into the logs in a more structured way. But for now, we
# have this so that we can compare it to people who follow through.
logger.info "Started signup from #{params[:email]}"
# Some stats
current_or_guest_user.signup_channel = params["source"]
current_or_guest_user.signup_referer = request.env["HTTP_REFERER"]
# STOP
when :authorizing
session[:fetcher] = Github.fetch_access_token current_or_guest_user, code
when :authorized
session[:next] = true
when :fetching_projects
session[:fetcher] = Github.tentacles "repos/repos", current_or_guest_user
when :list_projects
# TECHNICAL_DEBT: this is horrific, and just keeps getting worse
session[:allowed_urls] = @result.map { |p| p[:html_url] }
# stop
when :done
# Stay here until the user enters their password
end
# # TODO: start a worker which gets a list of builds
# # TODO: in the background, check them out, infer them, and stream the build to the user.
# # TODO: this means not waiting five minutes for the build to start!
end
def starting_state(code, access_token)
if code.nil? and access_token.nil?
:start
elsif code and access_token.nil? then
:authorizing
else
:fetching_projects
end
end
def next_state(state)
case state
when :start
# They need to click to github and come back, we can't do this for them.
:start
when :authorizing
:authorized
when :authorized
:fetching_projects
when :fetching_projects
:list_projects
when :list_projects
:done
when :done
:done # saturate
end
end
def step_for_state(state)
case state
when :start
[1,1]
when :authorizing
[1,2]
when :authorized
[1,3]
when :fetching_projects
[2,1]
when :list_projects
[2,2]
when :done
[3,1]
end
end
def form
projects = []
params.each do |key, value|
if value == "add_project"
projects.push key
end
end
# TECHNICAL_DEBT (minor for now): a better way to model github is to
# constantly sync projects and users into special GH models, and look them
# up directly.
# Add all projects the user has access to.
projects.each do |user_repo_pair|
username, projectname = user_repo_pair.split "/"
gh_url = Backend.blocking_worker "circle.backend.github-url/canonical-url", username, projectname
project = Project.where(:vcs_url => gh_url).first
allowed_urls = session[:allowed_urls] || []
session[:allowed_urls] = nil
allowed = allowed_urls.any? { |u| u == gh_url }
next if not allowed
if not project
project = Project.create :name => projectname, :vcs_url => gh_url
end
project.users << current_or_guest_user
project.save()
Github.add_deploy_key current_or_guest_user, project, username, projectname
Github.add_commit_hook username, projectname, current_or_guest_user
end
if current_user.sign_in_count > 0
redirect_to root_url
else
redirect_to join_url
end
end
# https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user
# Obviously, we're going to be using guest users. Do not call
# current_user anywhere in the controller until after we're certain
# the user must be logged in
def current_or_guest_user
if current_user
if session[:guest_user_id]
logging_in
# guest_user.destroy
session[:guest_user_id] = nil
end
current_user
else
guest_user
end
end
def guest_user
if session[:guest_user_id]
begin
return User.find session[:guest_user_id]
rescue Exception => e
end
end
u = create_guest_user
session[:guest_user_id] = u.id
u
end
def logging_in
end
def create_guest_user
id = BSON::ObjectId.new()
u = User.create(:_id => id, :email => "guest_#{id.to_s}")
u.save(:validate => false)
u
end
end
Fix the looping bug in the join page - going to simplify the state machine now.
class JoinController < ApplicationController
# When the user is not yet signed up, we get their project information from
# them first. We store all this in a "guest" user, and then at the end, we
# sign the guest user in, and update the information with their real info. The
# reason we go this way, instead of storing the information in a session, is
# that it works just fine this way, and changing it is a hassle. In
# particular, if we change it, we have to find a way for the front/back end to
# pass information around, which is a bit of a refactoring away from working
# well.
def all
@url = Github.authorization_url join_url
code = params[:code]
access_token = current_or_guest_user.github_access_token
state = starting_state(code, access_token)
session[:state] = state
@step, @substep = step_for_state(state)
start_job(state, params)
@user = current_or_guest_user # the body3_1 form will need access to this user.
end
def dynamic
state = session[:state]
fetcher = session[:fetcher]
if fetcher then
ready = Backend.worker_done? fetcher
if ready then
@result = Backend.wait_for_worker fetcher
session[:fetcher] = nil
end
end
# Just move through the states
if session[:next] then
ready = true
session[:next] = false
end
if ready then
state = next_state(state)
session[:state] = state
step, substep = step_for_state(state)
start_job(state, params)
body = render_to_string :partial => "body#{step}_#{substep}"
explanation = render_to_string :partial => "explanation#{step}"
end
keep_polling = (not ready.nil?)
packet = {
:step => step,
:substep => substep,
:ready => ready,
:keep_polling => keep_polling,
:state => state,
:body => body,
:explanation => explanation,
}.to_json
render :json => packet
end
def start_job(state, params)
# TODO: refactor this duplication
code = params[:code]
access_token = current_or_guest_user.github_access_token
# Start whatever job the state requires
case state
when :start
# TODO: put this into the logs in a more structured way. But for now, we
# have this so that we can compare it to people who follow through.
logger.info "Started signup from #{params[:email]}"
# Some stats
current_or_guest_user.signup_channel = params["source"]
current_or_guest_user.signup_referer = request.env["HTTP_REFERER"]
# STOP
when :authorizing
session[:fetcher] = Github.fetch_access_token current_or_guest_user, code
when :authorized
session[:next] = true
when :fetching_projects
session[:fetcher] = Github.tentacles "repos/repos", current_or_guest_user
when :list_projects
# TECHNICAL_DEBT: this is horrific, and just keeps getting worse
session[:allowed_urls] = @result.map { |p| p[:html_url] }
# stop
when :signup
session[:signup] = false
# Stay here until the user enters their password
end
# # TODO: start a worker which gets a list of builds
# # TODO: in the background, check them out, infer them, and stream the build to the user.
# # TODO: this means not waiting five minutes for the build to start!
end
def starting_state(code, access_token)
if code.nil? and access_token.nil?
:start
elsif code and access_token.nil?
:authorizing
elsif session[:signup]
:signup
else
:fetching_projects
end
end
def next_state(state)
case state
when :start
# They need to click to github and come back, we can't do this for them.
:start
when :authorizing
:authorized
when :authorized
:fetching_projects
when :fetching_projects
:list_projects
when :list_projects
:signup
when :signup
:signup # saturate
end
end
def step_for_state(state)
case state
when :start
[1,1]
when :authorizing
[1,2]
when :authorized
[1,3]
when :fetching_projects
[2,1]
when :list_projects
[2,2]
when :signup
[3,1]
end
end
def form
projects = []
params.each do |key, value|
if value == "add_project"
projects.push key
end
end
# TECHNICAL_DEBT (minor for now): a better way to model github is to
# constantly sync projects and users into special GH models, and look them
# up directly.
# Add all projects the user has access to.
projects.each do |user_repo_pair|
username, projectname = user_repo_pair.split "/"
gh_url = Backend.blocking_worker "circle.backend.github-url/canonical-url", username, projectname
project = Project.where(:vcs_url => gh_url).first
allowed_urls = session[:allowed_urls] || []
session[:allowed_urls] = nil
allowed = allowed_urls.any? { |u| u == gh_url }
next if not allowed
if not project
project = Project.create :name => projectname, :vcs_url => gh_url
end
project.users << current_or_guest_user
project.save()
Github.add_deploy_key current_or_guest_user, project, username, projectname
Github.add_commit_hook username, projectname, current_or_guest_user
end
if current_or_guest_user.sign_in_count > 0
redirect_to root_url
else
session[:signup] = true
redirect_to join_url
end
end
# https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user
# Obviously, we're going to be using guest users. Do not call
# current_user anywhere in the controller until after we're certain
# the user must be logged in
def current_or_guest_user
if current_user
if session[:guest_user_id]
logging_in
# guest_user.destroy
session[:guest_user_id] = nil
end
current_user
else
guest_user
end
end
def guest_user
if session[:guest_user_id]
begin
return User.find session[:guest_user_id]
rescue Exception => e
end
end
u = create_guest_user
session[:guest_user_id] = u.id
u
end
def logging_in
end
def create_guest_user
id = BSON::ObjectId.new()
u = User.create(:_id => id, :email => "guest_#{id.to_s}")
u.save(:validate => false)
u
end
end
|
class ListController < ApplicationController
before_filter :ensure_logged_in, except: [:latest, :hot, :category, :category_feed, :latest_feed, :hot_feed, :topics_by]
before_filter :set_category, only: [:category, :category_feed]
skip_before_filter :check_xhr
# Create our filters
[:latest, :hot, :favorited, :read, :posted, :unread, :new].each do |filter|
define_method(filter) do
list_opts = build_topic_list_options
user = current_user
if params[:user_id] && guardian.is_staff?
user = User.find(params[:user_id].to_i)
end
list = TopicQuery.new(user, list_opts).public_send("list_#{filter}")
list.more_topics_url = url_for(self.public_send "#{filter}_path".to_sym, list_opts.merge(format: 'json', page: next_page))
respond(list)
end
end
[:latest, :hot].each do |filter|
define_method("#{filter}_feed") do
anonymous_etag(@category) do
@title = "#{filter.capitalize} Topics"
@link = "#{Discourse.base_url}/#{filter}"
@description = I18n.t("rss_description.#{filter}")
@atom_link = "#{Discourse.base_url}/#{filter}.rss"
@topic_list = TopicQuery.new(current_user).public_send("list_#{filter}")
render 'list', formats: [:rss]
end
end
end
def topics_by
list_opts = build_topic_list_options
list = TopicQuery.new(current_user, list_opts).list_topics_by(fetch_user_from_params)
list.more_topics_url = url_for(topics_by_path(list_opts.merge(format: 'json', page: next_page)))
respond(list)
end
def category
query = TopicQuery.new(current_user, page: params[:page])
# If they choose uncategorized, return topics NOT in a category
if request_is_for_uncategorized?
list = query.list_uncategorized
else
if !@category
raise Discourse::NotFound
return
end
guardian.ensure_can_see!(@category)
list = query.list_category(@category)
end
list.more_topics_url = url_for(category_list_path(params[:category], page: next_page, format: "json"))
respond(list)
end
def category_feed
raise Discourse::InvalidParameters.new('Category RSS of "uncategorized"') if request_is_for_uncategorized?
guardian.ensure_can_see!(@category)
anonymous_etag(@category) do
@title = @category.name
@link = "#{Discourse.base_url}/category/#{@category.slug}"
@description = "#{I18n.t('topics_in_category', category: @category.name)} #{@category.description}"
@atom_link = "#{Discourse.base_url}/category/#{@category.slug}.rss"
@topic_list = TopicQuery.new.list_new_in_category(@category)
render 'list', formats: [:rss]
end
end
def popular_redirect
# We've renamed popular to latest. Use a redirect until we're sure we can
# safely remove this.
redirect_to latest_path, :status => 301
end
protected
def respond(list)
list.draft_key = Draft::NEW_TOPIC
list.draft_sequence = DraftSequence.current(current_user, Draft::NEW_TOPIC)
draft = Draft.get(current_user, list.draft_key, list.draft_sequence) if current_user
list.draft = draft
discourse_expires_in 1.minute
respond_to do |format|
format.html do
@list = list
store_preloaded('topic_list', MultiJson.dump(TopicListSerializer.new(list, scope: guardian)))
render 'list'
end
format.json do
render_serialized(list, TopicListSerializer)
end
end
end
def next_page
params[:page].to_i + 1
end
private
def set_category
slug = params.fetch(:category)
@category = Category.where("slug = ?", slug).includes(:featured_users).first || Category.where("id = ?", slug.to_i).includes(:featured_users).first
end
def request_is_for_uncategorized?
params[:category] == Slug.for(SiteSetting.uncategorized_name) ||
params[:category] == SiteSetting.uncategorized_name ||
params[:category] == 'uncategorized'
end
def build_topic_list_options
# html format means we need to parse exclude category (aka filter) from the site options top menu
menu_items = SiteSetting.top_menu_items
menu_item = menu_items.select { |item| item.query_should_exclude_category?(action_name, params[:format]) }.first
# exclude_category = 1. from params / 2. parsed from top menu / 3. nil
return {
page: params[:page],
topic_ids: param_to_integer_list(:topic_ids),
exclude_category: (params[:exclude_category] || menu_item.try(:filter))
}
end
end
Extract ListController#list_target_user
class ListController < ApplicationController
before_filter :ensure_logged_in, except: [:latest, :hot, :category, :category_feed, :latest_feed, :hot_feed, :topics_by]
before_filter :set_category, only: [:category, :category_feed]
skip_before_filter :check_xhr
# Create our filters
[:latest, :hot, :favorited, :read, :posted, :unread, :new].each do |filter|
define_method(filter) do
list_opts = build_topic_list_options
user = list_target_user
list = TopicQuery.new(user, list_opts).public_send("list_#{filter}")
list.more_topics_url = url_for(self.public_send "#{filter}_path".to_sym, list_opts.merge(format: 'json', page: next_page))
respond(list)
end
end
[:latest, :hot].each do |filter|
define_method("#{filter}_feed") do
anonymous_etag(@category) do
@title = "#{filter.capitalize} Topics"
@link = "#{Discourse.base_url}/#{filter}"
@description = I18n.t("rss_description.#{filter}")
@atom_link = "#{Discourse.base_url}/#{filter}.rss"
@topic_list = TopicQuery.new(current_user).public_send("list_#{filter}")
render 'list', formats: [:rss]
end
end
end
def topics_by
list_opts = build_topic_list_options
list = TopicQuery.new(current_user, list_opts).list_topics_by(fetch_user_from_params)
list.more_topics_url = url_for(topics_by_path(list_opts.merge(format: 'json', page: next_page)))
respond(list)
end
def category
query = TopicQuery.new(current_user, page: params[:page])
# If they choose uncategorized, return topics NOT in a category
if request_is_for_uncategorized?
list = query.list_uncategorized
else
if !@category
raise Discourse::NotFound
return
end
guardian.ensure_can_see!(@category)
list = query.list_category(@category)
end
list.more_topics_url = url_for(category_list_path(params[:category], page: next_page, format: "json"))
respond(list)
end
def category_feed
raise Discourse::InvalidParameters.new('Category RSS of "uncategorized"') if request_is_for_uncategorized?
guardian.ensure_can_see!(@category)
anonymous_etag(@category) do
@title = @category.name
@link = "#{Discourse.base_url}/category/#{@category.slug}"
@description = "#{I18n.t('topics_in_category', category: @category.name)} #{@category.description}"
@atom_link = "#{Discourse.base_url}/category/#{@category.slug}.rss"
@topic_list = TopicQuery.new.list_new_in_category(@category)
render 'list', formats: [:rss]
end
end
def popular_redirect
# We've renamed popular to latest. Use a redirect until we're sure we can
# safely remove this.
redirect_to latest_path, :status => 301
end
protected
def respond(list)
list.draft_key = Draft::NEW_TOPIC
list.draft_sequence = DraftSequence.current(current_user, Draft::NEW_TOPIC)
draft = Draft.get(current_user, list.draft_key, list.draft_sequence) if current_user
list.draft = draft
discourse_expires_in 1.minute
respond_to do |format|
format.html do
@list = list
store_preloaded('topic_list', MultiJson.dump(TopicListSerializer.new(list, scope: guardian)))
render 'list'
end
format.json do
render_serialized(list, TopicListSerializer)
end
end
end
def next_page
params[:page].to_i + 1
end
private
def set_category
slug = params.fetch(:category)
@category = Category.where("slug = ?", slug).includes(:featured_users).first || Category.where("id = ?", slug.to_i).includes(:featured_users).first
end
def request_is_for_uncategorized?
params[:category] == Slug.for(SiteSetting.uncategorized_name) ||
params[:category] == SiteSetting.uncategorized_name ||
params[:category] == 'uncategorized'
end
def build_topic_list_options
# html format means we need to parse exclude category (aka filter) from the site options top menu
menu_items = SiteSetting.top_menu_items
menu_item = menu_items.select { |item| item.query_should_exclude_category?(action_name, params[:format]) }.first
# exclude_category = 1. from params / 2. parsed from top menu / 3. nil
return {
page: params[:page],
topic_ids: param_to_integer_list(:topic_ids),
exclude_category: (params[:exclude_category] || menu_item.try(:filter))
}
end
def list_target_user
if params[:user_id] && guardian.is_staff?
User.find(params[:user_id].to_i)
else
current_user
end
end
end
|
class MailController < ApplicationController
no_login_required
skip_before_filter :verify_authenticity_token
def create
@page = Page.find(params[:page_id])
@page.request, @page.response = request, response
config, part_page = config_and_page(@page)
mail = Mail.new(part_page, config, params[:mailer])
@page.last_mail = part_page.last_mail = mail
process_mail(mail, config)
if mail.send
redirect_to (config[:redirect_to] || "#{@page.url}#mail_sent")
else
render :text => @page.render
end
end
private
# Hook here to do additional things, like check a CAPTCHA
def process_mail(mail, config)
end
def config_and_page(page)
until page.part(:mailer) or (not page.parent)
page = page.parent
end
string = page.render_part(:mailer)
[(string.empty? ? {} : YAML::load(string).symbolize_keys), page]
end
end
Removed trailing \n
class MailController < ApplicationController
no_login_required
skip_before_filter :verify_authenticity_token
def create
@page = Page.find(params[:page_id])
@page.request, @page.response = request, response
config, part_page = config_and_page(@page)
mail = Mail.new(part_page, config, params[:mailer])
@page.last_mail = part_page.last_mail = mail
process_mail(mail, config)
if mail.send
redirect_to (config[:redirect_to] || "#{@page.url}#mail_sent")
else
render :text => @page.render
end
end
private
# Hook here to do additional things, like check a CAPTCHA
def process_mail(mail, config)
end
def config_and_page(page)
until page.part(:mailer) or (not page.parent)
page = page.parent
end
string = page.render_part(:mailer)
[(string.empty? ? {} : YAML::load(string).symbolize_keys), page]
end
end |
class MainController < ApplicationController
layout false
before_filter :authenticate_user!
def index
render file: Rails.root.join('public', 'index.html')
end
end
Show error message when submodule is not initialzed
class MainController < ApplicationController
layout false
before_filter :authenticate_user!
def index
admin_app = Rails.root.join('public', 'index.html')
if File.exists? admin_app
render file: admin_app
else
render text: "Cannot find #{admin_app}, please run 'git submodule update --init'"
end
end
end
|
class MainController < ApplicationController
layout 'capacitor'
def index
@candidates ||= []
@sla = CloudCapacitor::Settings.capacitor["sla"]
@cpu_limit = CloudCapacitor::Settings.capacitor["cpu_limit"]
@mem_limit = CloudCapacitor::Settings.capacitor["mem_limit"]
@low_deviation = CloudCapacitor::Settings.capacitor["low_deviation"]
@medium_deviation = CloudCapacitor::Settings.capacitor["medium_deviation"]
@workload_approach ||= :optimistic
@configuration_approach ||= :optimistic
end
def eval_performance
@workloadlist = params[:workloadlist].map!{|x| x.to_i}
@workload_approach = params[:workload_approach].to_sym
@configuration_approach = params[:configuration_approach].to_sym
CloudCapacitor::Settings.capacitor["sla"] = params[:sla].to_i if !params[:sla].empty?
# CloudCapacitor::Settings.capacitor["cpu_limit"] = params[:cpu_limit].to_f if !params[:cpu_limit].empty?
# CloudCapacitor::Settings.capacitor["mem_limit"] = params[:mem_limit].to_f if !params[:mem_limit].empty?
# CloudCapacitor::Settings.capacitor["low_deviation"] = params[:low_deviation].to_f if !params[:low_deviation].empty?
# CloudCapacitor::Settings.capacitor["medium_deviation"] = params[:medium_deviation].to_f if !params[:medium_deviation].empty?
@sla = CloudCapacitor::Settings.capacitor.sla
case params[:graph_mode].to_sym
when :capacity
@graph_mode = :strict
when :cost
@graph_mode = :price
else
@graph_mode = :strict
end
# @cpu_limit = CloudCapacitor::Settings.capacitor.cpu_limit
# @mem_limit = CloudCapacitor::Settings.capacitor.mem_limit
# @low_deviation = CloudCapacitor::Settings.capacitor.low_deviation
# @medium_deviation = CloudCapacitor::Settings.capacitor.medium_deviation
puts @graph_mode.class
capacitor = CloudCapacitor::Capacitor.new @graph_mode
capacitor.executor = CloudCapacitor::Executors::DummyExecutor.new
capacitor.strategy = CloudCapacitor::Strategies::MCG_Strategy.new
capacitor.strategy.approach workload: @workload_approach,
config: @configuration_approach
@candidates = capacitor.run_for(*@workloadlist)
@cost = capacitor.run_cost
@executions = capacitor.executions
@trace = capacitor.execution_trace
@full_trace = capacitor.results_trace
@configs = capacitor.deployment_space.configs_by_price.clone
@configs.sort_by! { |c| [c.category, c.price] }
@reference = ReferenceResult.load
evaluate_results_precision
@global_precision = calculate_global_precision
@global_recall = calculate_global_recall
@global_f_measure = calculate_global_f_measure
render 'results'
end
def about
end
def report
capacitor = CloudCapacitor::Capacitor.new
capacitor.executor = CloudCapacitor::Executors::DummyExecutor.new
capacitor.strategy = CloudCapacitor::Strategies::MCG_Strategy.new
workloads = [100,200,300,400,500,600,700,800,900,1000]
approaches = [:optimistic, :pessimistic, :conservative, :random]
slas = (1..10).map{|i| i * 10_000}
heuristic_name = { optimistic:
{ optimistic: "OO",
pessimistic: "OP",
conservative: "OC",
random: "OR" },
pessimistic:
{ optimistic: "PO",
pessimistic: "PP",
conservative: "PC",
random: "PR" },
conservative:
{ optimistic: "CO",
pessimistic: "CP",
conservative: "CC",
random: "CR" },
random:
{ optimistic: "RO",
pessimistic: "RP",
conservative: "RC",
random: "RR" }
}
approaches.each do |wkl_approach|
approaches.each do |config_approach|
heuristic = heuristic_name[wkl_approach][config_approach]
File.open("#{heuristic}_heuristic_result.csv", "wt") do |result|
result.puts "heuristic,workload,configuration,metsla,sla,predict" #.split(",")
slas.each do |sla|
CloudCapacitor::Settings.capacitor["sla"] = sla
capacitor.strategy.approach workload: wkl_approach, config: config_approach
puts "Running: Heuristic = #{heuristic} and SLA = #{sla}"
capacitor.run_for(*workloads)
puts "Run finished! Writing output"
full_trace = capacitor.results_trace
workloads.each do |w|
# Format: {"1.m3_medium": {100: {met_sla: false, executed: true, execution: 1}}}
full_trace.keys.each do |cfg|
exec = full_trace[cfg][w]
exec.nil? || exec == {} ? metsla = nil : metsla = exec[:met_sla]
exec.nil? || exec == {} ? predict = nil : predict = !exec[:executed]
result.puts "#{heuristic},#{w},#{cfg},#{metsla},#{sla},#{predict}" #.split(",")
end
end
end
end
end
end
redirect_to action: :index
end
private
def calculate_global_precision
(@confusion_matrix[:tp] / (@confusion_matrix[:tp] + @confusion_matrix[:fp])).round(3)
end
def calculate_global_recall
(@confusion_matrix[:tp] / (@confusion_matrix[:tp] + @confusion_matrix[:fn])).round(3)
end
def calculate_global_f_measure
(2 * ( (@global_precision * @global_recall) / (@global_precision + @global_recall) )).round(3)
end
def find_reference(workload, config)
i = @reference.index { |r| r[0] == workload && r[1] == config}
@reference[i][2] # returns the real execution response time
end
def evaluate_results_precision
@wkl_confusion_matrix = {}
@confusion_matrix = {tp: 0.0, fp: 0.0, tn: 0.0, fn: 0.0}
@workloadlist.each do |wkl|
@wkl_confusion_matrix[wkl] = {tp: 0.0, fp: 0.0, tn: 0.0, fn: 0.0}
end
@full_trace.each_pair do |cfg, wkl|
wkl.each_pair do |w, exec|
if exec != {}
reference_value = find_reference(w, cfg)
if exec[:met_sla] && reference_value <= @sla
exec.update({correctness: "ok"})
@confusion_matrix[:tp] += 1
@wkl_confusion_matrix[w][:tp] += 1
elsif !exec[:met_sla] && reference_value > @sla
exec.update({correctness: "ok"})
@confusion_matrix[:tn] += 1
@wkl_confusion_matrix[w][:tn] += 1
elsif !exec[:met_sla] && reference_value <= @sla
exec.update({correctness: "nok"})
@confusion_matrix[:fn] += 1
@wkl_confusion_matrix[w][:fn] += 1
elsif exec[:met_sla] && reference_value > @sla
exec.update({correctness: "nok"})
@confusion_matrix[:fp] += 1
@wkl_confusion_matrix[w][:fp] += 1
end
end
end
end
puts "Confusion Matrix = #{@confusion_matrix}"
end
end
Reporting results for price Deployment Graph
class MainController < ApplicationController
layout 'capacitor'
def index
@candidates ||= []
@sla = CloudCapacitor::Settings.capacitor["sla"]
@cpu_limit = CloudCapacitor::Settings.capacitor["cpu_limit"]
@mem_limit = CloudCapacitor::Settings.capacitor["mem_limit"]
@low_deviation = CloudCapacitor::Settings.capacitor["low_deviation"]
@medium_deviation = CloudCapacitor::Settings.capacitor["medium_deviation"]
@workload_approach ||= :optimistic
@configuration_approach ||= :optimistic
end
def eval_performance
@workloadlist = params[:workloadlist].map!{|x| x.to_i}
@workload_approach = params[:workload_approach].to_sym
@configuration_approach = params[:configuration_approach].to_sym
CloudCapacitor::Settings.capacitor["sla"] = params[:sla].to_i if !params[:sla].empty?
# CloudCapacitor::Settings.capacitor["cpu_limit"] = params[:cpu_limit].to_f if !params[:cpu_limit].empty?
# CloudCapacitor::Settings.capacitor["mem_limit"] = params[:mem_limit].to_f if !params[:mem_limit].empty?
# CloudCapacitor::Settings.capacitor["low_deviation"] = params[:low_deviation].to_f if !params[:low_deviation].empty?
# CloudCapacitor::Settings.capacitor["medium_deviation"] = params[:medium_deviation].to_f if !params[:medium_deviation].empty?
@sla = CloudCapacitor::Settings.capacitor.sla
case params[:graph_mode].to_sym
when :capacity
@graph_mode = :strict
when :cost
@graph_mode = :price
else
@graph_mode = :strict
end
# @cpu_limit = CloudCapacitor::Settings.capacitor.cpu_limit
# @mem_limit = CloudCapacitor::Settings.capacitor.mem_limit
# @low_deviation = CloudCapacitor::Settings.capacitor.low_deviation
# @medium_deviation = CloudCapacitor::Settings.capacitor.medium_deviation
puts @graph_mode.class
capacitor = CloudCapacitor::Capacitor.new @graph_mode
capacitor.executor = CloudCapacitor::Executors::DummyExecutor.new
capacitor.strategy = CloudCapacitor::Strategies::MCG_Strategy.new
capacitor.strategy.approach workload: @workload_approach,
config: @configuration_approach
@candidates = capacitor.run_for(*@workloadlist)
@cost = capacitor.run_cost
@executions = capacitor.executions
@trace = capacitor.execution_trace
@full_trace = capacitor.results_trace
@configs = capacitor.deployment_space.configs_by_price.clone
@configs.sort_by! { |c| [c.category, c.price] }
@reference = ReferenceResult.load
evaluate_results_precision
@global_precision = calculate_global_precision
@global_recall = calculate_global_recall
@global_f_measure = calculate_global_f_measure
render 'results'
end
def about
end
def report
[:strict, :price].each do |mode|
mode_name = (mode == :strict) ? "capacity" : "price"
capacitor = CloudCapacitor::Capacitor.new mode
capacitor.executor = CloudCapacitor::Executors::DummyExecutor.new
capacitor.strategy = CloudCapacitor::Strategies::MCG_Strategy.new
workloads = [100,200,300,400,500,600,700,800,900,1000]
approaches = [:optimistic, :pessimistic, :conservative, :random]
slas = (1..10).map{|i| i * 10_000}
heuristic_name = { optimistic:
{ optimistic: "OO",
pessimistic: "OP",
conservative: "OC",
random: "OR" },
pessimistic:
{ optimistic: "PO",
pessimistic: "PP",
conservative: "PC",
random: "PR" },
conservative:
{ optimistic: "CO",
pessimistic: "CP",
conservative: "CC",
random: "CR" },
random:
{ optimistic: "RO",
pessimistic: "RP",
conservative: "RC",
random: "RR" }
}
approaches.each do |wkl_approach|
approaches.each do |config_approach|
heuristic = heuristic_name[wkl_approach][config_approach]
File.open("#{heuristic}_heuristic_#{mode_name}_mode_result.csv", "wt") do |result|
result.puts "heuristic,workload,configuration,metsla,sla,predict" #.split(",")
slas.each do |sla|
CloudCapacitor::Settings.capacitor["sla"] = sla
capacitor.strategy.approach workload: wkl_approach, config: config_approach
puts "Running: Heuristic = #{heuristic} Mode = #{mode_name} and SLA = #{sla}"
capacitor.run_for(*workloads)
puts "Run finished! Writing output"
full_trace = capacitor.results_trace
workloads.each do |w|
# Format: {"1.m3_medium": {100: {met_sla: false, executed: true, execution: 1}}}
full_trace.keys.each do |cfg|
exec = full_trace[cfg][w]
exec.nil? || exec == {} ? metsla = nil : metsla = exec[:met_sla]
exec.nil? || exec == {} ? predict = nil : predict = !exec[:executed]
result.puts "#{heuristic},#{w},#{cfg},#{metsla},#{sla},#{predict}" #.split(",")
end
end
end
end
end
end
end
redirect_to action: :index
end
private
def calculate_global_precision
(@confusion_matrix[:tp] / (@confusion_matrix[:tp] + @confusion_matrix[:fp])).round(3)
end
def calculate_global_recall
(@confusion_matrix[:tp] / (@confusion_matrix[:tp] + @confusion_matrix[:fn])).round(3)
end
def calculate_global_f_measure
(2 * ( (@global_precision * @global_recall) / (@global_precision + @global_recall) )).round(3)
end
def find_reference(workload, config)
i = @reference.index { |r| r[0] == workload && r[1] == config}
@reference[i][2] # returns the real execution response time
end
def evaluate_results_precision
@wkl_confusion_matrix = {}
@confusion_matrix = {tp: 0.0, fp: 0.0, tn: 0.0, fn: 0.0}
@workloadlist.each do |wkl|
@wkl_confusion_matrix[wkl] = {tp: 0.0, fp: 0.0, tn: 0.0, fn: 0.0}
end
@full_trace.each_pair do |cfg, wkl|
wkl.each_pair do |w, exec|
if exec != {}
reference_value = find_reference(w, cfg)
if exec[:met_sla] && reference_value <= @sla
exec.update({correctness: "ok"})
@confusion_matrix[:tp] += 1
@wkl_confusion_matrix[w][:tp] += 1
elsif !exec[:met_sla] && reference_value > @sla
exec.update({correctness: "ok"})
@confusion_matrix[:tn] += 1
@wkl_confusion_matrix[w][:tn] += 1
elsif !exec[:met_sla] && reference_value <= @sla
exec.update({correctness: "nok"})
@confusion_matrix[:fn] += 1
@wkl_confusion_matrix[w][:fn] += 1
elsif exec[:met_sla] && reference_value > @sla
exec.update({correctness: "nok"})
@confusion_matrix[:fp] += 1
@wkl_confusion_matrix[w][:fp] += 1
end
end
end
end
puts "Confusion Matrix = #{@confusion_matrix}"
end
end
|
#!/usr/bin/ruby
x = []
10.times {x << 0.00}
300.times {x << 2.00}
200.times {x << 1.00}
Kp = 1.0
Ki = 0.1
Kd = 4.0
previous_error = 0.0
integral = 0.0
actual_position = 0.0
dt = 1.0
response = 0.1
x.each do |setpoint|
error = setpoint - actual_position
integral = integral + error*dt
derivative = (error - previous_error) / dt
output = (Kp*error) + (Ki*integral) + (Kd*derivative)
previous_error = error
actual_position += output * response
puts "#{output},#{setpoint},#{actual_position}"
end
cleaning
#!/usr/bin/ruby
# this script generates the data:
# ./pid.rb > data.csv
x = []
10.times {x << 0.00}
300.times {x << 2.00}
200.times {x << 1.00}
Kp = 1.0
Ki = 0.1
Kd = 4.0
Dt = 1.0
Response = 0.1
previous_error = 0.0
integral = 0.0
actual_position = 0.0
x.each do |setpoint|
# PID controller
error = setpoint - actual_position
integral = integral + error*Dt
derivative = (error - previous_error) / Dt
output = (Kp*error) + (Ki*integral) + (Kd*derivative)
previous_error = error
# "environment"
actual_position += output * Response
puts "#{output},#{setpoint},#{actual_position}"
end
|
class MainController < ApplicationController
def index
@page_title = t('home_title')
opts = {:page => params[:page], :order => 'statuses.id DESC', :include => :user}
@tweets = Status.paginate opts
end
def tweetstream
@page_title = t('tweetstream')
opts = {:page => params[:page], :order => 'statuses.id DESC', :include => :user, :q => params[:q]}
#opts[:conditions] = ["statuses.text like ?", "%#{params[:q]}%"] unless params[:q].blank?
@tweets = Status.paginate opts
end
def stats
@most_followed = Person.all :include => :user, :order => 'users.followers_count desc', :limit => 5
@most_active = Person.all :include => :user, :order => 'users.statuses_count desc', :limit => 5
@most_new_seven_days = Person.all(:include => {:user => :stats}, :order => 'stats.followers_change_last_seven_days desc', :limit => 5).map{|p| [p, p.user.stats.followers_change_last_seven_days]}
@most_new_thirty_days = Person.all(:include => {:user => :stats}, :order => 'stats.followers_change_last_thirty_days desc', :limit => 5).map{|p| [p, p.user.stats.followers_change_last_thirty_days]}
end
protected
end
Fix bug on stats page when Person doesn't have a User
class MainController < ApplicationController
def index
@page_title = t('home_title')
opts = {:page => params[:page], :order => 'statuses.id DESC', :include => :user}
@tweets = Status.paginate opts
end
def tweetstream
@page_title = t('tweetstream')
opts = {:page => params[:page], :order => 'statuses.id DESC', :include => :user, :q => params[:q]}
#opts[:conditions] = ["statuses.text like ?", "%#{params[:q]}%"] unless params[:q].blank?
@tweets = Status.paginate opts
end
def stats
@most_followed = Person.all :joins => :user, :order => 'users.followers_count desc', :limit => 5
@most_active = Person.all :joins => :user, :order => 'users.statuses_count desc', :limit => 5
@most_new_seven_days = Person.all(:joins => {:user => :stats}, :order => 'stats.followers_change_last_seven_days desc', :limit => 5).map{|p| [p, p.user.stats.followers_change_last_seven_days]}
@most_new_thirty_days = Person.all(:joins => {:user => :stats}, :order => 'stats.followers_change_last_thirty_days desc', :limit => 5).map{|p| [p, p.user.stats.followers_change_last_thirty_days]}
end
protected
end
|
class MapsController < AssetsController
def map
add_breadcrumb "Map"
end
# Called via Ajax to get the map marker for a selected asset
# Asset is identified by its object key in the params hash
def marker
@marker = {}
a = Rails.application.config.asset_base_class_name.constantize.find_by(:object_key => params[:object_key])
if asset
asset = Rails.application.config.asset_base_class_name.constantize.get_typed_asset(a)
if asset.mappable?
@marker = asset.get_map_marker
end
end
end
# Called via AJAX to get dynamic content via AJAX
def map_popup
str = ""
a = Rails.application.config.asset_base_class_name.constantize.find_by(:object_key => params[:id])
if a
asset = Rails.application.config.asset_base_class_name.constantize.get_typed_asset(a)
if asset.mappable?
str = render_to_string(:partial => "/shared/map_popup", :locals => { :asset => asset })
end
end
render json: str.to_json
end
# Called via AJAX to get dynamic content via AJAX
def map_cluster_popup
assets = Rails.application.config.asset_base_class_name.constantize.where(:object_key => params[:object_keys]).order(:asset_type_id, :asset_subtype_id, purchase_date: :desc)
str = render_to_string(:partial => "/shared/map_cluster_popup", :locals => { :assets => assets })
render json: str.to_json
end
end
remove order
class MapsController < AssetsController
def map
add_breadcrumb "Map"
end
# Called via Ajax to get the map marker for a selected asset
# Asset is identified by its object key in the params hash
def marker
@marker = {}
a = Rails.application.config.asset_base_class_name.constantize.find_by(:object_key => params[:object_key])
if asset
asset = Rails.application.config.asset_base_class_name.constantize.get_typed_asset(a)
if asset.mappable?
@marker = asset.get_map_marker
end
end
end
# Called via AJAX to get dynamic content via AJAX
def map_popup
str = ""
a = Rails.application.config.asset_base_class_name.constantize.find_by(:object_key => params[:id])
if a
asset = Rails.application.config.asset_base_class_name.constantize.get_typed_asset(a)
if asset.mappable?
str = render_to_string(:partial => "/shared/map_popup", :locals => { :asset => asset })
end
end
render json: str.to_json
end
# Called via AJAX to get dynamic content via AJAX
def map_cluster_popup
assets = Rails.application.config.asset_base_class_name.constantize.where(:object_key => params[:object_keys])
str = render_to_string(:partial => "/shared/map_cluster_popup", :locals => { :assets => assets })
render json: str.to_json
end
end
|
class PacsController < EmbeddedToolsController
def exclude_syndicated_iframe_resizer?
true
end
protected
def category_id
nil
end
helper_method :category_id
end
Add a temporary authentication on pacs tool
Disclaimer: I don't think there should be an automated test for this since
it will be removed in a few days.
class PacsController < EmbeddedToolsController
before_action :authenticate, if: :authentication_required?
def exclude_syndicated_iframe_resizer?
true
end
protected
def authenticate
authenticate_or_request_with_http_basic do |username, password|
Authenticable.authenticate(username, password)
end
end
def authentication_required?
Authenticable.staging? || Rails.env.production?
end
def category_id
nil
end
helper_method :category_id
end
|
class QuasController < ApplicationController
before_action :set_qua, only: [:show, :edit, :update, :destroy, :show_image]
# GET /quas
# GET /quas.json
def index
@quas = Qua.all
end
# GET /quas/1
# GET /quas/1.json
def show
end
# GET /quas/new
def new
@qua = Qua.new
end
# GET /quas/1/edit
def edit
end
# POST /quas
# POST /quas.json
def create
@qua = Qua.new(qua_params)
respond_to do |format|
if @qua.save
format.html { redirect_to @qua, notice: 'Qua was successfully created.' }
format.json { render :show, status: :created, location: @qua }
else
format.html { render :new }
format.json { render json: @qua.errors, status: :unprocessable_entity }
end
end
end
def create_ajax
@qua = Qua.new(qua_params)
respond_to do |format|
if @qua.save
format.json {
render json: { :qua => @qua }
}
else
format.json { render json: @qua.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /quas/1
# PATCH/PUT /quas/1.json
def update
respond_to do |format|
if @qua.update(qua_params)
format.html { redirect_to @qua, notice: 'Qua was successfully updated.' }
format.json { render :show, status: :ok, location: @qua }
else
format.html { render :edit }
format.json { render json: @qua.errors, status: :unprocessable_entity }
end
end
end
# DELETE /quas/1
# DELETE /quas/1.json
def destroy
@qua.destroy
respond_to do |format|
format.html { redirect_to quas_url, notice: 'Qua was successfully destroyed.' }
format.json { head :no_content }
end
end
def show_image
send_data @image.image1, :type => 'image/jpeg', :disposition => 'inline'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_qua
@qua = Qua.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def qua_params
params.require(:qua).permit(:name, :latitude, :longitude,
:quality, :effect, :url, :stay_required, :price,
:image1_caption, :image1, :image2_caption, :image2, :image3_caption, :image3)
end
end
ref #51 Modify variable name in qua controller
class QuasController < ApplicationController
before_action :set_qua, only: [:show, :edit, :update, :destroy, :show_image]
# GET /quas
# GET /quas.json
def index
@quas = Qua.all
end
# GET /quas/1
# GET /quas/1.json
def show
end
# GET /quas/new
def new
@qua = Qua.new
end
# GET /quas/1/edit
def edit
end
# POST /quas
# POST /quas.json
def create
@qua = Qua.new(qua_params)
respond_to do |format|
if @qua.save
format.html { redirect_to @qua, notice: 'Qua was successfully created.' }
format.json { render :show, status: :created, location: @qua }
else
format.html { render :new }
format.json { render json: @qua.errors, status: :unprocessable_entity }
end
end
end
def create_ajax
@qua = Qua.new(qua_params)
respond_to do |format|
if @qua.save
format.json {
render json: { :qua => @qua }
}
else
format.json { render json: @qua.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /quas/1
# PATCH/PUT /quas/1.json
def update
respond_to do |format|
if @qua.update(qua_params)
format.html { redirect_to @qua, notice: 'Qua was successfully updated.' }
format.json { render :show, status: :ok, location: @qua }
else
format.html { render :edit }
format.json { render json: @qua.errors, status: :unprocessable_entity }
end
end
end
# DELETE /quas/1
# DELETE /quas/1.json
def destroy
@qua.destroy
respond_to do |format|
format.html { redirect_to quas_url, notice: 'Qua was successfully destroyed.' }
format.json { head :no_content }
end
end
def show_image
send_data @qua.image1, :type => 'image/jpeg', :disposition => 'inline'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_qua
@qua = Qua.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def qua_params
params.require(:qua).permit(:name, :latitude, :longitude,
:quality, :effect, :url, :stay_required, :price,
:image1_caption, :image1, :image2_caption, :image2, :image3_caption, :image3)
end
end
|
class SiteController < ApplicationController
def root
@departments = Department.all
@count = Paper.count.round(-1)
end
def imprint
end
def faq
end
def recent
@papers = Paper
.order(created_at: :desc, reference: :desc)
.page params[:page]
fresh_when last_modified: @papers.maximum(:updated_at), public: true
end
end
order departments by id
class SiteController < ApplicationController
def root
@departments = Department.all.order(id: :asc)
@count = Paper.count.round(-1)
end
def imprint
end
def faq
end
def recent
@papers = Paper
.order(created_at: :desc, reference: :desc)
.page params[:page]
fresh_when last_modified: @papers.maximum(:updated_at), public: true
end
end
|
class TagsController < ApplicationController
respond_to :json
def index
@tags = Tag.all
respond_with @tags
end
end
Fix in tags controller.
class TagsController < ApplicationController
def index
@tags = Tag.all
render json: @tags
end
end |
#/usr/bin/env ruby
require './state'
require './client'
require 'debugger'
class Game
game = State.new
nc = Client.new
nc.login
game.initBoard
puts "Enter Game to Accept:"
gameId = gets.chomp
# make first move if true
if nc.acceptGame(gameId)
puts "First Move is mine"
nc.move(game.evalMove)
end
while not game.gameOver? do
nc.waitForMove
game.humanMove(nc.getOpponentMove)
break if game.gameOver?
nc.move(game.evalMove)
end
nc.exit
end
Update network game to use new paths
#/usr/bin/env ruby
require File.expand_path('../../lib/state.rb', __FILE__)
require File.expand_path('../../lib/client.rb', __FILE__)
require 'debugger'
class Game
game = State.new
nc = Client.new
nc.login
game.initBoard
puts "Enter Game to Accept:"
gameId = gets.chomp
# make first move if true
if nc.acceptGame(gameId)
puts "First Move is mine"
nc.move(game.negamaxMove)
end
while not game.gameOver? do
nc.waitForMove
game.humanMove(nc.getOpponentMove)
break if game.gameOver?
nc.move(game.negamaxMove)
end
nc.exit
end
|
class TagsController < ApplicationController
autocomplete :tag, :name, full: true
def show
@tag = Tag.find_by_name params[:id]
if @tag
@query = @tag.name
issues = Issue.find_by_tag(@tag).order(updated_at: :desc).page(params[:issue_page])
issues = issues.intersects(current_group.profile.location) if current_group
@issues = IssueDecorator.decorate_collection issues
unfiltered_results = MessageThread.find_by_tag(@tag).includes(:issue, :group).order(updated_at: :desc)
threads = Kaminari.paginate_array(
unfiltered_results.select{ |t| permitted_to?(:show, t) }).page(params[:thread_page])
@threads = ThreadListDecorator.decorate_collection threads
@library_items = Library::Item.find_by_tag(@tag).order('updated_at desc').page(params[:library_page])
else
@unrecognised_tag_name = params[:id]
end
end
def index
@tags = Rails.cache.fetch("Tag.top_tags(200)", expires: 1.day) do
Tag.top_tags(200)
end
end
end
Cache the query result, not the query
class TagsController < ApplicationController
autocomplete :tag, :name, full: true
def show
@tag = Tag.find_by_name params[:id]
if @tag
@query = @tag.name
issues = Issue.find_by_tag(@tag).order(updated_at: :desc).page(params[:issue_page])
issues = issues.intersects(current_group.profile.location) if current_group
@issues = IssueDecorator.decorate_collection issues
unfiltered_results = MessageThread.find_by_tag(@tag).includes(:issue, :group).order(updated_at: :desc)
threads = Kaminari.paginate_array(
unfiltered_results.select{ |t| permitted_to?(:show, t) }).page(params[:thread_page])
@threads = ThreadListDecorator.decorate_collection threads
@library_items = Library::Item.find_by_tag(@tag).order('updated_at desc').page(params[:library_page])
else
@unrecognised_tag_name = params[:id]
end
end
def index
@tags = Rails.cache.fetch("Tag.top_tags", expires: 1.day) do
Tag.top_tags(200).to_a
end
end
end
|
#encoding: utf-8
class TaxaController < ApplicationController
caches_page :range, :if => Proc.new {|c| c.request.format == :geojson}
caches_action :show, :expires_in => 1.day, :if => Proc.new {|c|
c.session.blank? || c.session['warden.user.user.key'].blank?
}
caches_action :describe, :expires_in => 1.day, :if => Proc.new {|c|
c.session.blank? || c.session['warden.user.user.key'].blank?
}
include TaxaHelper
include Shared::WikipediaModule
before_filter :return_here, :only => [:index, :show, :flickr_tagger, :curation, :synonyms]
before_filter :authenticate_user!, :only => [:edit_photos, :update_photos,
:update_colors, :tag_flickr_photos, :tag_flickr_photos_from_observations,
:flickr_photos_tagged, :add_places, :synonyms]
before_filter :curator_required, :only => [:new, :create, :edit, :update,
:destroy, :curation, :refresh_wikipedia_summary, :merge, :synonyms]
before_filter :load_taxon, :only => [:edit, :update, :destroy, :photos,
:children, :graft, :describe, :edit_photos, :update_photos, :edit_colors,
:update_colors, :add_places, :refresh_wikipedia_summary, :merge,
:observation_photos, :range, :schemes, :tip]
before_filter :limit_page_param_for_thinking_sphinx, :only => [:index,
:browse, :search]
before_filter :ensure_flickr_write_permission, :only => [
:flickr_photos_tagged, :tag_flickr_photos,
:tag_flickr_photos_from_observations]
cache_sweeper :taxon_sweeper, :only => [:update, :destroy, :update_photos]
GRID_VIEW = "grid"
LIST_VIEW = "list"
BROWSE_VIEWS = [GRID_VIEW, LIST_VIEW]
ALLOWED_SHOW_PARTIALS = %w(chooser)
MOBILIZED = [:show, :index]
before_filter :unmobilized, :except => MOBILIZED
before_filter :mobilized, :only => MOBILIZED
#
# GET /observations
# GET /observations.xml
#
# @param name: Return all taxa where name is an EXACT match
# @param q: Return all taxa where the name begins with q
#
def index
find_taxa unless request.format == :html
begin
@taxa.try(:total_entries)
rescue ThinkingSphinx::SphinxError => e
Rails.logger.error "[ERROR #{Time.now}] Failed sphinx search: #{e}"
@taxa = WillPaginate::Collection.new(1,30,0)
end
respond_to do |format|
format.html do # index.html.erb
@featured_taxa = Taxon.all(:conditions => "featured_at IS NOT NULL",
:order => "featured_at DESC", :limit => 100,
:include => [:iconic_taxon, :photos, :taxon_names])
if @featured_taxa.blank?
@featured_taxa = Taxon.all(:limit => 100, :conditions => [
"taxa.wikipedia_summary IS NOT NULL AND " +
"photos.id IS NOT NULL AND " +
"taxa.observations_count > 1"
], :include => [:iconic_taxon, :photos, :taxon_names],
:order => "taxa.id DESC")
end
# Shuffle the taxa (http://snippets.dzone.com/posts/show/2994)
@featured_taxa = @featured_taxa.sort_by{rand}[0..10]
flash[:notice] = @status unless @status.blank?
if params[:q]
find_taxa
render :action => :search
else
@iconic_taxa = Taxon::ICONIC_TAXA
@recent = Observation.all(
:select => "DISTINCT ON (taxon_id) *",
:from => "(SELECT * from observations WHERE taxon_id IS NOT NULL ORDER BY observed_on DESC NULLS LAST LIMIT 10) AS obs",
:include => {:taxon => [:taxon_names]},
:limit => 5
).sort_by(&:id).reverse
end
end
format.mobile do
if @taxa.blank?
page = params[:page].to_i
page = 1 if page < 1
@taxon_photos = TaxonPhoto.paginate(:page => page, :per_page => 32, :order => "id DESC")
@taxa = Taxon.all(:conditions => ["id IN (?)", @taxon_photos.map{|tp| tp.taxon_id}])
end
end
format.xml do
render(:xml => @taxa.to_xml(
:include => :taxon_names, :methods => [:common_name]))
end
format.json do
@taxa = Taxon::ICONIC_TAXA if @taxa.blank? && params[:q].blank?
options = Taxon.default_json_options
options[:include].merge!(
:iconic_taxon => {:only => [:id, :name]},
:taxon_names => {:only => [:id, :name, :lexicon]}
)
options[:methods] += [:common_name, :image_url, :default_name]
render :json => @taxa.to_json(options)
end
end
end
def show
if params[:entry] == 'widget'
flash[:notice] = "Welcome to #{CONFIG.site_name_short}! Click 'Add an observtion' to the lower right. You'll be prompted to sign in/sign up if you haven't already"
end
@taxon ||= Taxon.find_by_id(params[:id].to_i, :include => [:taxon_names]) if params[:id]
return render_404 unless @taxon
if !@taxon.conservation_status.blank? && @taxon.conservation_status > Taxon::IUCN_LEAST_CONCERN
@conservation_status_name = @taxon.conservation_status_name
@conservation_status_source = @taxon.conservation_status_source
end
respond_to do |format|
format.html do
if @taxon.name == 'Life' && !@taxon.parent_id
return redirect_to(:action => 'index')
end
@amphibiaweb = amphibiaweb_description?
@try_amphibiaweb = try_amphibiaweb?
@children = @taxon.children.all(
:include => :taxon_names,
:conditions => {:is_active => @taxon.is_active}
).sort_by{|c| c.name}
@ancestors = @taxon.ancestors.all(:include => :taxon_names)
@iconic_taxa = Taxon::ICONIC_TAXA
@check_listed_taxa = ListedTaxon.page(1).
select("min(listed_taxa.id) AS id, listed_taxa.place_id, listed_taxa.taxon_id, min(listed_taxa.list_id) AS list_id, min(establishment_means) AS establishment_means").
includes(:place, :list).
group(:place_id, :taxon_id).
where("place_id IS NOT NULL AND taxon_id = ?", @taxon)
@sorted_check_listed_taxa = @check_listed_taxa.sort_by{|lt| lt.place.place_type || 0}.reverse
@places = @check_listed_taxa.map{|lt| lt.place}.uniq{|p| p.id}
@countries = @taxon.places.all(
:select => "places.id, place_type, code",
:conditions => ["place_type = ?", Place::PLACE_TYPE_CODES['Country']]
).uniq{|p| p.id}
if @countries.size == 1 && @countries.first.code == 'US'
@us_states = @taxon.places.all(
:select => "places.id, place_type, code",
:conditions => [
"place_type = ? AND parent_id = ?", Place::PLACE_TYPE_CODES['State'],
@countries.first.id
]
).uniq{|p| p.id}
end
@taxon_links = if @taxon.species_or_lower?
# fetch all relevant links
TaxonLink.for_taxon(@taxon).includes(:taxon)
else
# fetch links without species only
TaxonLink.for_taxon(@taxon).where(:species_only => false).includes(:taxon)
end
tl_place_ids = @taxon_links.map(&:place_id).compact
if !tl_place_ids.blank? # && !@places.blank?
if @places.blank?
@taxon_links.reject! {|tl| tl.place_id}
else
# fetch listed taxa for this taxon with places matching the links
place_listed_taxa = ListedTaxon.where("place_id IN (?)", tl_place_ids).where(:taxon_id => @taxon)
# remove links that have a place_id set but don't have a corresponding listed taxon
@taxon_links.reject! do |tl|
tl.place_id && place_listed_taxa.detect{|lt| lt.place_id == tl.place_id}.blank?
end
end
end
@taxon_links.uniq!{|tl| tl.url}
@taxon_links = @taxon_links.sort_by{|tl| tl.taxon.ancestry || ''}.reverse
@observations = Observation.of(@taxon).recently_added.all(:limit => 3)
@photos = Rails.cache.fetch(@taxon.photos_cache_key) do
@taxon.photos_with_backfill(:skip_external => true, :limit => 24)
end
if logged_in?
@listed_taxa = ListedTaxon.all(
:include => [:list],
:conditions => [
"lists.user_id = ? AND listed_taxa.taxon_id = ?",
current_user, @taxon
])
@listed_taxa_by_list_id = @listed_taxa.index_by{|lt| lt.list_id}
@current_user_lists = current_user.lists.includes(:rules)
@lists_rejecting_taxon = @current_user_lists.select do |list|
if list.is_a?(LifeList)
list.rules.map {|rule| rule.validates?(@taxon)}.include?(false)
else
false
end
end
end
@taxon_range = @taxon.taxon_ranges.without_geom.first
@taxon_gbif = "#{@taxon.name.gsub(' ','+')}*"
@show_range = @taxon_range
@colors = @taxon.colors if @taxon.species_or_lower?
unless @taxon.is_active?
@taxon_change = TaxonChange.taxon(@taxon).last
end
render :action => 'show'
end
format.mobile do
if @taxon.species_or_lower? && @taxon.species
@siblings = @taxon.species.siblings.all(:limit => 100, :include => [:photos, :taxon_names]).sort_by{|t| t.name}
@siblings.delete_if{|s| s.id == @taxon.id}
else
@children = @taxon.children.all(:limit => 100, :include => [:photos, :taxon_names]).sort_by{|t| t.name}
end
end
format.xml do
render :xml => @taxon.to_xml(
:include => [:taxon_names, :iconic_taxon],
:methods => [:common_name]
)
end
format.json do
if (partial = params[:partial]) && ALLOWED_SHOW_PARTIALS.include?(partial)
@taxon.html = render_to_string(:partial => "#{partial}.html.erb", :object => @taxon)
end
render(:json => @taxon.to_json(
:include => [:taxon_names, :iconic_taxon],
:methods => [:common_name, :image_url, :html])
)
end
format.node { render :json => jit_taxon_node(@taxon) }
end
end
def tip
@observation = Observation.find_by_id(params[:observation_id]) if params[:observation_id]
if @observation
@places = @observation.system_places
end
render :layout => false
end
def new
@taxon = Taxon.new(:name => params[:name])
end
def create
@taxon = Taxon.new
return unless presave
@taxon.attributes = params[:taxon]
@taxon.creator = current_user
if @taxon.save
flash[:notice] = 'Taxon was successfully created.'
if locked_ancestor = @taxon.ancestors.is_locked.first
flash[:notice] += " Heads up: you just added a descendant of a " +
"locked taxon (<a href='/taxa/#{locked_ancestor.id}'>" +
"#{locked_ancestor.name}</a>). Please consider merging this " +
"into an existing taxon instead."
end
redirect_to :action => 'show', :id => @taxon
else
render :action => 'new'
end
end
def edit
descendant_options = {:joins => [:taxon], :conditions => @taxon.descendant_conditions}
taxon_options = {:conditions => {:taxon_id => @taxon}}
@observations_exist = Observation.first(taxon_options) || Observation.first(descendant_options)
@listed_taxa_exist = ListedTaxon.first(taxon_options) || ListedTaxon.first(descendant_options)
@identifications_exist = Identification.first(taxon_options) || Identification.first(descendant_options)
@descendants_exist = @taxon.descendants.first
@taxon_range = TaxonRange.without_geom.first(:conditions => {:taxon_id => @taxon})
end
def update
return unless presave
if @taxon.update_attributes(params[:taxon])
flash[:notice] = 'Taxon was successfully updated.'
if locked_ancestor = @taxon.ancestors.is_locked.first
flash[:notice] += " Heads up: you just added a descendant of a " +
"locked taxon (<a href='/taxa/#{locked_ancestor.id}'>" +
"#{locked_ancestor.name}</a>). Please consider merging this " +
"into an existing taxon instead."
end
redirect_to taxon_path(@taxon)
return
else
render :action => 'edit'
end
end
def destroy
@taxon.destroy
flash[:notice] = "Taxon deleted."
redirect_to :action => 'index'
end
## Custom actions ############################################################
# /taxa/browse?q=bird
# /taxa/browse?q=bird&places=1,2&colors=4,5
# TODO: /taxa/browse?q=bird&places=usa-ca-berkeley,usa-ct-clinton&colors=blue,black
def search
@q = params[:q] = params[:q].to_s.sanitize_encoding
match_mode = :all
# Wrap the query in modifiers to ensure exact matches show first
if @q.blank?
q = @q
else
q = sanitize_sphinx_query(@q)
# for some reason 1-term queries don't return an exact match first if enclosed
# in quotes, so we only use them for multi-term queries
q = if q =~ /\s/
"\"^#{q}$\" | #{q}"
else
"^#{q}$ | #{q}"
end
match_mode = :extended
end
drill_params = {}
if params[:taxon_id] && (@taxon = Taxon.find_by_id(params[:taxon_id].to_i))
drill_params[:ancestors] = @taxon.id
end
if params[:is_active] == "true" || params[:is_active].blank?
@is_active = true
drill_params[:is_active] = true
elsif params[:is_active] == "false"
@is_active = false
drill_params[:is_active] = false
else
@is_active = params[:is_active]
end
if params[:iconic_taxa] && @iconic_taxa_ids = params[:iconic_taxa].split(',')
@iconic_taxa_ids = @iconic_taxa_ids.map(&:to_i)
@iconic_taxa = Taxon.find(@iconic_taxa_ids)
drill_params[:iconic_taxon_id] = @iconic_taxa_ids
end
# if params[:places] && @place_ids = params[:places].split(',')
# @place_ids = @place_ids.map(&:to_i)
# @places = Place.find(@place_ids)
# drill_params[:places] = @place_ids
# end
if params[:colors] && @color_ids = params[:colors].split(',')
@color_ids = @color_ids.map(&:to_i)
@colors = Color.find(@color_ids)
drill_params[:colors] = @color_ids
end
per_page = params[:per_page] ? params[:per_page].to_i : 24
per_page = 100 if per_page > 100
page = params[:page] ? params[:page].to_i : 1
@facets = Taxon.facets(q, :page => page, :per_page => per_page,
:with => drill_params,
:include => [:taxon_names, :photos],
:field_weights => {:name => 2},
:match_mode => match_mode)
if @facets[:iconic_taxon_id]
@faceted_iconic_taxa = Taxon.all(
:conditions => ["id in (?)", @facets[:iconic_taxon_id].keys],
:include => [:taxon_names, :photos]
)
@faceted_iconic_taxa = Taxon.sort_by_ancestry(@faceted_iconic_taxa)
@faceted_iconic_taxa_by_id = @faceted_iconic_taxa.index_by(&:id)
end
if @facets[:colors]
@faceted_colors = Color.all(:conditions => ["id in (?)", @facets[:colors].keys])
@faceted_colors_by_id = @faceted_colors.index_by(&:id)
end
@taxa = @facets.for(drill_params)
begin
@taxa.blank?
rescue ThinkingSphinx::SphinxError, Riddle::OutOfBoundsError => e
Rails.logger.error "[ERROR #{Time.now}] Failed sphinx search: #{e}"
@taxa = WillPaginate::Collection.new(1,30,0)
end
do_external_lookups
unless @taxa.blank?
# if there's an exact match among the hits, make sure it's first
if exact_index = @taxa.index{|t| t.all_names.map(&:downcase).include?(params[:q].to_s.downcase)}
if exact_index > 0
@taxa.unshift @taxa.delete_at(exact_index)
end
# otherwise try and hit the db directly. Sphinx doesn't always seem to behave properly
elsif params[:page].to_i <= 1 && (exact = Taxon.where("lower(name) = ?", params[:q].to_s.downcase.strip).first)
@taxa.unshift exact
end
end
respond_to do |format|
format.html do
@view = BROWSE_VIEWS.include?(params[:view]) ? params[:view] : GRID_VIEW
flash[:notice] = @status unless @status.blank?
if @taxa.blank?
@all_iconic_taxa = Taxon::ICONIC_TAXA
@all_colors = Color.all
end
if params[:partial]
render :partial => "taxa/#{params[:partial]}.html.erb", :locals => {
:js_link => params[:js_link]
}
else
render :browse
end
end
format.json do
options = Taxon.default_json_options
options[:include].merge!(
:iconic_taxon => {:only => [:id, :name]},
:taxon_names => {:only => [:id, :name, :lexicon, :is_valid]}
)
options[:methods] += [:common_name, :image_url, :default_name]
render :json => @taxa.to_json(options)
end
end
end
def autocomplete
@q = params[:q] || params[:term]
@is_active = if params[:is_active] == "true" || params[:is_active].blank?
true
elsif params[:is_active] == "false"
false
else
params[:is_active]
end
scope = TaxonName.includes(:taxon => :taxon_names).
where("lower(taxon_names.name) LIKE ?", "#{@q.to_s.downcase}%").
limit(30).scoped
scope = scope.where("taxa.is_active = ?", @is_active) unless @is_active == "any"
@taxon_names = scope.sort_by{|tn| tn.taxon.ancestry || ''}
exact_matches = []
@taxon_names.each_with_index do |taxon_name, i|
next unless taxon_name.name.downcase.strip == @q.to_s.downcase.strip
exact_matches << @taxon_names.delete_at(i)
end
if exact_matches.blank?
exact_matches = TaxonName.all(:include => {:taxon => :taxon_names},
:conditions => ["lower(taxon_names.name) = ?", @q.to_s.downcase])
end
@taxon_names = exact_matches + @taxon_names
@taxa = @taxon_names.map do |taxon_name|
taxon = taxon_name.taxon
taxon.html = view_context.render_in_format(:html, :partial => "chooser.html.erb",
:object => taxon, :comname => taxon_name.is_scientific_names? ? nil : taxon_name)
taxon
end
respond_to do |format|
format.json do
render :json => @taxa.to_json(:methods => [:html])
end
end
end
def browse
redirect_to :action => "search"
end
def occur_in
@taxa = Taxon.occurs_in(params[:swlng], params[:swlat], params[:nelng],
params[:nelat], params[:startDate], params[:endDate])
@taxa.sort! do |a,b|
(a.common_name ? a.common_name.name : a.name) <=> (b.common_name ? b.common_name.name : b.name)
end
respond_to do |format|
format.html
format.json do
render :text => @taxa.to_json(
:methods => [:id, :common_name] )
end
end
end
#
# List child taxa of this taxon
#
def children
respond_to do |format|
format.html { redirect_to taxon_path(@taxon) }
format.xml do
render :xml => @taxon.children.to_xml(
:include => :taxon_names, :methods => [:common_name] )
end
format.json do
options = Taxon.default_json_options
options[:include].merge!(:taxon_names => {:only => [:id, :name, :lexicon]})
options[:methods] += [:common_name]
render :json => @taxon.children.all(:include => [{:taxon_photos => :photo}, :taxon_names]).to_json(options)
end
end
end
def photos
limit = params[:limit].to_i
limit = 24 if limit.blank? || limit == 0
limit = 50 if limit > 50
begin
@photos = Rails.cache.fetch(@taxon.photos_with_external_cache_key) do
@taxon.photos_with_backfill(:limit => 50).map do |fp|
fp.api_response = nil
fp
end
end[0..(limit-1)]
rescue Timeout::Error => e
Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}"
@photos = @taxon.photos
end
if params[:partial]
key = {:controller => 'taxa', :action => 'photos', :id => @taxon.id, :partial => params[:partial]}
if fragment_exist?(key)
content = read_fragment(key)
else
content = if @photos.blank?
'<div class="description">No matching photos.</div>'
else
render_to_string :partial => "taxa/#{params[:partial]}", :collection => @photos
end
write_fragment(key, content)
end
render :layout => false, :text => content
else
render :layout => false, :partial => "photos", :locals => {
:photos => @photos
}
end
rescue SocketError => e
raise unless Rails.env.development?
Rails.logger.debug "[DEBUG] Looks like you're offline, skipping flickr"
render :text => "You're offline."
end
def schemes
@scheme_taxa = TaxonSchemeTaxon.all(:conditions => {:taxon_id => @taxon.id})
end
def map
@cloudmade_key = CONFIG.cloudmade.key
@bing_key = CONFIG.bing.key
if @taxon = Taxon.find_by_id(params[:id].to_i)
load_single_taxon_map_data(@taxon)
end
taxon_ids = if params[:taxa].is_a?(Array)
params[:taxa]
elsif params[:taxa].is_a?(String)
params[:taxa].split(',')
end
if taxon_ids
@taxa = Taxon.all(:conditions => ["id IN (?)", taxon_ids.map{|t| t.to_i}], :limit => 20)
@taxon_ranges = TaxonRange.without_geom.all(:conditions => ["taxon_id IN (?)", @taxa]).group_by(&:taxon_id)
@taxa_data = taxon_ids.map do |taxon_id|
next unless taxon = @taxa.detect{|t| t.id == taxon_id.to_i}
taxon.as_json(:only => [:id, :name, :is_active]).merge(
:range_url => @taxon_ranges[taxon.id] ? taxon_range_geom_url(taxon.id, :format => "geojson") : nil,
:observations_url => taxon.observations.exists? ? observations_of_url(taxon, :format => "geojson") : nil,
)
end
@bounds = if !@taxon_ranges.blank?
TaxonRange.calculate(:extent, :geom, :conditions => ["taxon_id IN (?)", @taxa])
else
Observation.of(@taxa.first).calculate(:extent, :geom)
end
if @bounds
@extent = [
{:lon => @bounds.lower_corner.x, :lat => @bounds.lower_corner.y},
{:lon => @bounds.upper_corner.x, :lat => @bounds.upper_corner.y}
]
end
end
if params[:test]
@child_taxa = @taxon.descendants.of_rank(Taxon::SPECIES).all(:limit => 10)
@child_taxon_ranges = TaxonRange.without_geom.all(:conditions => ["taxon_id IN (?)", @child_taxa]).group_by(&:taxon_id)
@children = @child_taxa.map do |child|
{
:id => child.id,
:range_url => @child_taxon_ranges[child.id] ? taxon_range_geom_url(child.id, :format => "geojson") : nil,
:observations_url => observations_of_url(child, :format => "geojson"),
:name => child.name
}
end
end
end
def range
@taxon_range = if request.format == :geojson
@taxon.taxon_ranges.simplified.first
else
@taxon.taxon_ranges.first
end
unless @taxon_range
flash[:error] = "Taxon doesn't have a range"
redirect_to @taxon
return
end
respond_to do |format|
format.html { redirect_to taxon_map_path(@taxon) }
format.kml { redirect_to @taxon_range.range.url }
format.geojson { render :json => [@taxon_range].to_geojson }
end
end
def observation_photos
if per_page = params[:per_page]
per_page = per_page.to_i > 50 ? 50 : per_page.to_i
end
observations = if params[:q].blank?
Observation.of(@taxon).paginate(:page => params[:page],
:per_page => per_page, :include => [:photos],
:conditions => "photos.id IS NOT NULL")
else
Observation.search(params[:q], :page => params[:page],
:per_page => per_page, :with => {:has_photos => true, :taxon_id => @taxon.id})
end
@photos = observations.map(&:photos).flatten
render :partial => 'photos/photo_list_form', :locals => {
:photos => @photos,
:index => params[:index],
:local_photos => false }
end
def edit_photos
render :layout => false
end
def add_places
unless params[:tab].blank?
@places = case params[:tab]
when 'countries'
@countries = Place.all(:order => "name",
:conditions => ["place_type = ?", Place::PLACE_TYPE_CODES["Country"]]).compact
when 'us_states'
if @us = Place.find_by_name("United States")
@us.children.all(:order => "name").compact
else
[]
end
else
[]
end
@listed_taxa = @taxon.listed_taxa.all(:conditions => ["place_id IN (?)", @places],
:select => "DISTINCT ON (place_id) listed_taxa.*")
@listed_taxa_by_place_id = @listed_taxa.index_by(&:place_id)
render :partial => 'taxa/add_to_place_link', :collection => @places, :locals => {
:skip_map => true
}
return
end
if request.post?
if params[:paste_places]
add_places_from_paste
else
add_places_from_search
end
respond_to do |format|
format.json do
@places.each_with_index do |place, i|
@places[i].html = view_context.render_in_format(:html, :partial => 'add_to_place_link', :object => place)
end
render :json => @places.to_json(:methods => [:html])
end
end
return
end
render :layout => false
end
private
def add_places_from_paste
place_names = params[:paste_places].split(",").map{|p| p.strip.downcase}.reject(&:blank?)
@places = Place.all(:conditions => [
"place_type = ? AND name IN (?)",
Place::PLACE_TYPE_CODES['Country'], place_names
])
@places ||= []
(place_names - @places.map{|p| p.name.strip.downcase}).each do |new_place_name|
ydn_places = GeoPlanet::Place.search(new_place_name, :count => 1, :type => "Country")
next if ydn_places.blank?
@places << Place.import_by_woeid(ydn_places.first.woeid)
end
@listed_taxa = @places.map do |place|
place.check_list.try(:add_taxon, @taxon, :user_id => current_user.id)
end.select{|p| p.valid?}
@listed_taxa_by_place_id = @listed_taxa.index_by{|lt| lt.place_id}
end
def add_places_from_search
search_for_places
@listed_taxa = @taxon.listed_taxa.all(:conditions => ["place_id IN (?)", @places],
:select => "DISTINCT ON (place_id) listed_taxa.*")
@listed_taxa_by_place_id = @listed_taxa.index_by(&:place_id)
end
public
def find_places
@limit = 5
@js_link = params[:js_link]
@partial = params[:partial]
search_for_places
render :layout => false
end
def update_photos
photos = retrieve_photos
errors = photos.map do |p|
p.valid? ? nil : p.errors.full_messages
end.flatten.compact
@taxon.photos = photos
@taxon.save
unless photos.count == 0
Taxon.delay(:priority => INTEGRITY_PRIORITY).update_ancestor_photos(@taxon.id, photos.first.id)
end
if errors.blank?
flash[:notice] = "Taxon photos updated!"
else
flash[:error] = "Some of those photos couldn't be saved: #{errors.to_sentence.downcase}"
end
redirect_to taxon_path(@taxon)
rescue Errno::ETIMEDOUT
flash[:error] = "Request timed out!"
redirect_back_or_default(taxon_path(@taxon))
rescue Koala::Facebook::APIError => e
raise e unless e.message =~ /OAuthException/
flash[:error] = "Facebook needs the owner of that photo to re-confirm their connection to #{CONFIG.site_name_short}."
redirect_back_or_default(taxon_path(@taxon))
end
def describe
@amphibiaweb = amphibiaweb_description?
if @amphibiaweb
taxon_names = @taxon.taxon_names.all(
:conditions => {:lexicon => TaxonName::LEXICONS[:SCIENTIFIC_NAMES]},
:order => "is_valid, id desc")
if @xml = get_amphibiaweb(taxon_names)
render :partial => "amphibiaweb"
return
else
@before_wikipedia = '<div class="notice status">AmphibiaWeb didn\'t have info on this taxon, showing Wikipedia instead.</div>'
end
end
@title = @taxon.wikipedia_title.blank? ? @taxon.name : @taxon.wikipedia_title
wikipedia
end
def refresh_wikipedia_summary
begin
summary = @taxon.set_wikipedia_summary
rescue Timeout::Error => e
error_text = e.message
end
if summary.blank?
error_text ||= "Could't retrieve the Wikipedia " +
"summary for #{@taxon.name}. Make sure there is actually a " +
"corresponding article on Wikipedia."
render :status => 404, :text => error_text
else
render :text => summary
end
end
def update_colors
unless params[:taxon] && params[:taxon][:color_ids]
redirect_to @taxon
end
params[:taxon][:color_ids].delete_if(&:blank?)
@taxon.colors = Color.find(params[:taxon].delete(:color_ids))
respond_to do |format|
if @taxon.save
format.html { redirect_to @taxon }
format.json do
render :json => @taxon
end
else
msg = "There were some problems saving those colors: #{@taxon.errors.full_messages.join(', ')}"
format.html do
flash[:error] = msg
redirect_to @taxon
end
format.json do
render :json => {:errors => msg}, :status => :unprocessable_entity
end
end
end
end
def graft
begin
lineage = ratatosk.graft(@taxon)
rescue Timeout::Error => e
@error_message = e.message
rescue RatatoskGraftError => e
@error_message = e.message
end
@taxon.reload
@error_message ||= "Graft failed. Please graft manually by editing the taxon." unless @taxon.grafted?
respond_to do |format|
format.html do
flash[:error] = @error_message if @error_message
redirect_to(edit_taxon_path(@taxon))
end
format.js do
if @error_message
render :status => :unprocessable_entity, :text => @error_message
else
render :text => "Taxon grafted to #{@taxon.parent.name}"
end
end
format.json do
if @error_message
render :status => :unprocessable_entity, :json => {:error => @error_message}
else
render :json => {:msg => "Taxon grafted to #{@taxon.parent.name}"}
end
end
end
end
def merge
@keeper = Taxon.find_by_id(params[:taxon_id].to_i)
if @keeper && @keeper.id == @taxon.id
msg = "Failed to merge taxon #{@taxon.id} (#{@taxon.name}) into taxon #{@keeper.id} (#{@keeper.name}). You can't merge a taxon with itself."
respond_to do |format|
format.html do
flash[:error] = msg
redirect_back_or_default(@taxon)
return
end
format.js do
render :text => msg, :status => :unprocessable_entity, :layout => false
return
end
format.json { render :json => {:error => msg} }
end
end
if request.post? && @keeper
if @taxon.id == @keeper_id
flash[:error] = "Can't merge a taxon with itself."
return redirect_to :action => "merge", :id => @taxon
end
@keeper.merge(@taxon)
flash[:notice] = "#{@taxon.name} (#{@taxon.id}) merged into " +
"#{@keeper.name} (#{@keeper.id}). #{@taxon.name} (#{@taxon.id}) " +
"has been deleted."
respond_to do |format|
format.html do
if session[:return_to].to_s =~ /#{@taxon.id}/
redirect_to @keeper
else
redirect_back_or_default(@keeper)
end
end
format.json { render :json => @keeper }
end
return
end
respond_to do |format|
format.html
format.js do
@taxon_change = TaxonChange.input_taxon(@taxon).output_taxon(@keeper).first
@taxon_change ||= TaxonChange.input_taxon(@keeper).output_taxon(@taxon).first
render :partial => "taxa/merge"
end
format.json { render :json => @keeper }
end
end
def curation
@flags = Flag.paginate(:page => params[:page],
:include => :user,
:conditions => "resolved = false AND flaggable_type = 'Taxon'",
:order => "flags.id desc")
@resolved_flags = Flag.all(:limit => 5,
:include => [:user, :resolver],
:conditions => "resolved = true AND flaggable_type = 'Taxon'",
:order => "flags.id desc")
life = Taxon.find_by_name('Life')
@ungrafted = Taxon.roots.active.paginate(:conditions => ["id != ?", life],
:page => 1, :per_page => 100, :include => [:taxon_names])
end
def synonyms
filters = params[:filters] || {}
@iconic_taxon = filters[:iconic_taxon]
@rank = filters[:rank]
scope = Taxon.active.scoped
scope = scope.self_and_descendants_of(@iconic_taxon) unless @iconic_taxon.blank?
scope = scope.of_rank(@rank) unless @rank.blank?
@taxa = scope.paginate(
:page => params[:page],
:per_page => 100,
:order => "rank_level",
:joins => "LEFT OUTER JOIN taxa t ON t.name = taxa.name",
:conditions => ["t.id IS NOT NULL AND t.id != taxa.id AND t.is_active = ?", true]
)
@synonyms = Taxon.active.all(
:conditions => ["name IN (?)", @taxa.map{|t| t.name}],
:include => [:taxon_names, :taxon_schemes]
)
@synonyms_by_name = @synonyms.group_by{|t| t.name}
end
def flickr_tagger
f = get_flickraw
@taxon ||= Taxon.find_by_id(params[:id].to_i) if params[:id]
@taxon ||= Taxon.find_by_id(params[:taxon_id].to_i) if params[:taxon_id]
@flickr_photo_ids = [params[:flickr_photo_id], params[:flickr_photos]].flatten.compact
@flickr_photos = @flickr_photo_ids.map do |flickr_photo_id|
begin
original = f.photos.getInfo(:photo_id => flickr_photo_id)
flickr_photo = FlickrPhoto.new_from_api_response(original)
if flickr_photo && @taxon.blank?
if @taxa = flickr_photo.to_taxa
@taxon = @taxa.sort_by{|t| t.ancestry || ''}.last
end
end
flickr_photo
rescue FlickRaw::FailedResponse => e
flash[:notice] = "Sorry, one of those Flickr photos either doesn't exist or " +
"you don't have permission to view it."
nil
end
end.compact
@tags = @taxon ? @taxon.to_tags : []
respond_to do |format|
format.html
format.json { render :json => @tags}
end
end
def tag_flickr_photos
# Post tags to flickr
if params[:flickr_photos].blank?
flash[:notice] = "You didn't select any photos to tag!"
redirect_to :action => 'flickr_tagger' and return
end
unless logged_in? && current_user.flickr_identity
flash[:notice] = "Sorry, you need to be signed in and have a " +
"linked Flickr account to post tags directly to Flickr."
redirect_to :action => 'flickr_tagger' and return
end
flickr = get_flickraw
photos = FlickrPhoto.all(:conditions => ["native_photo_id IN (?)", params[:flickr_photos]], :include => :observations)
params[:flickr_photos].each do |flickr_photo_id|
tags = params[:tags]
photo = nil
if photo = photos.detect{|p| p.native_photo_id == flickr_photo_id}
tags += " " + photo.observations.map{|o| "inaturalist:observation=#{o.id}"}.join(' ')
tags.strip!
end
tag_flickr_photo(flickr_photo_id, tags, :flickr => flickr)
return redirect_to :action => "flickr_tagger" unless flash[:error].blank?
end
flash[:notice] = "Your photos have been tagged!"
redirect_to :action => 'flickr_photos_tagged',
:flickr_photos => params[:flickr_photos], :tags => params[:tags]
end
def tag_flickr_photos_from_observations
if params[:o].blank?
flash[:error] = "You didn't select any observations."
return redirect_to :back
end
@observations = current_user.observations.all(
:conditions => ["id IN (?)", params[:o].split(',')],
:include => [:photos, {:taxon => :taxon_names}]
)
if @observations.blank?
flash[:error] = "No observations matching those IDs."
return redirect_to :back
end
if @observations.map(&:user_id).uniq.size > 1 || @observations.first.user_id != current_user.id
flash[:error] = "You don't have permission to edit those photos."
return redirect_to :back
end
flickr = get_flickraw
flickr_photo_ids = []
@observations.each do |observation|
observation.photos.each do |photo|
next unless photo.is_a?(FlickrPhoto)
next unless observation.taxon
tags = observation.taxon.to_tags
tags << "inaturalist:observation=#{observation.id}"
tag_flickr_photo(photo.native_photo_id, tags, :flickr => flickr)
unless flash[:error].blank?
return redirect_to :back
end
flickr_photo_ids << photo.native_photo_id
end
end
redirect_to :action => 'flickr_photos_tagged', :flickr_photos => flickr_photo_ids
end
def flickr_photos_tagged
flickr = get_flickraw
@tags = params[:tags]
if params[:flickr_photos].blank?
flash[:error] = "No Flickr photos tagged!"
return redirect_to :action => "flickr_tagger"
end
@flickr_photos = params[:flickr_photos].map do |flickr_photo_id|
fp = flickr.photos.getInfo(:photo_id => flickr_photo_id)
FlickrPhoto.new_from_flickraw(fp, :user => current_user)
end
@observations = current_user.observations.all(
:include => :photos,
:conditions => [
"photos.native_photo_id IN (?) AND photos.type = ?",
@flickr_photos.map(&:native_photo_id), FlickrPhoto.to_s
]
)
@observations_by_native_photo_id = {}
@observations.each do |observation|
observation.photos.each do |flickr_photo|
@observations_by_native_photo_id[flickr_photo.native_photo_id] = observation
end
end
end
def tree
@taxon = Taxon.find_by_id(params[:id], :include => [:taxon_names, :photos])
@taxon ||= Taxon.find_by_id(params[:taxon_id].to_i, :include => [:taxon_names, :photos])
unless @taxon
@taxon = Taxon.find_by_name('Life')
@taxon ||= Taxon.iconic_taxa.first.parent
end
@iconic_taxa = Taxon::ICONIC_TAXA
end
# Try to find a taxon from urls like /taxa/Animalia or /taxa/Homo_sapiens
def try_show
name, format = params[:q].to_s.sanitize_encoding.split('_').join(' ').split('.')
request.format = format if request.format.blank? && !format.blank?
name = name.to_s.downcase
# Try to look by its current unique name
unless @taxon
begin
taxa = Taxon.all(:conditions => ["unique_name = ?", name], :limit => 2) unless @taxon
rescue ActiveRecord::StatementInvalid, PGError => e
raise e unless e.message =~ /invalid byte sequence/ || e.message =~ /incomplete multibyte character/
name = name.encode('UTF-8')
taxa = Taxon.all(:conditions => ["unique_name = ?", name], :limit => 2)
end
@taxon = taxa.first if taxa.size == 1
end
# Try to look by its current scientifc name
unless @taxon
begin
taxa = Taxon.all(:conditions => ["lower(name) = ?", name], :limit => 2) unless @taxon
rescue ActiveRecord::StatementInvalid => e
raise e unless e.message =~ /invalid byte sequence/
name = name.encode('UTF-8')
taxa = Taxon.all(:conditions => ["lower(name) = ?", name], :limit => 2)
end
@taxon = taxa.first if taxa.size == 1
end
# Try to find a unique TaxonName
unless @taxon
begin
taxon_names = TaxonName.all(:conditions => ["lower(name) = ?", name], :limit => 2)
rescue ActiveRecord::StatementInvalid => e
raise e unless e.message =~ /invalid byte sequence/
name = name.encode('UTF-8')
taxon_names = TaxonName.all(:conditions => ["lower(name) = ?", name], :limit => 2)
end
if taxon_names.size == 1
@taxon = taxon_names.first.taxon
# Redirect to the currently accepted sciname if this isn't an accepted sciname
unless taxon_names.first.is_valid?
return redirect_to :action => @taxon.name.split.join('_')
end
end
end
# Redirect to a canonical form
if @taxon
canonical = (@taxon.unique_name || @taxon.name).split.join('_')
taxon_names ||= @taxon.taxon_names.all
acceptable_names = [@taxon.unique_name, @taxon.name].compact.map{|n| n.split.join('_')} +
taxon_names.map{|tn| tn.name.split.join('_')}
unless acceptable_names.include?(params[:q])
redirect_target = if params[:action].to_s.split.join('_') == @taxon.name.split.join('_')
@taxon.name.split.join('_')
else
canonical
end
return redirect_to :action => redirect_target
end
end
# TODO: if multiple exact matches, render a disambig page with status 300 (Mulitple choices)
unless @taxon
return redirect_to :action => 'search', :q => name
else
params.delete(:q)
return_here
show
end
end
## Protected / private actions ###############################################
private
def find_taxa
find_options = {
:order => "#{Taxon.table_name}.name ASC",
:include => :taxon_names
}
@qparams = {}
if params[:q]
@qparams[:q] = params[:q]
find_options[:conditions] = [ "#{Taxon.table_name}.name LIKE ?",
'%' + params[:q].split(' ').join('%') + '%' ]
elsif params[:name]
@qparams[:name] = params[:name]
find_options[:conditions] = [ "name = ?", params[:name] ]
elsif params[:names]
names = if params[:names].is_a?(String)
params[:names].split(',')
else
params[:names]
end
taxon_names = TaxonName.where("name IN (?)", names).limit(100)
find_options[:conditions] = ["taxa.is_active = ? AND taxa.id IN (?)", true, taxon_names.map(&:taxon_id).uniq]
else
find_options[:conditions] = ["is_iconic = ?", true]
find_options[:order] = :ancestry
end
if params[:limit]
@qparams[:limit] = params[:limit]
find_options[:limit] = params[:limit]
else
find_options[:page] = params[:page] || 1
find_options[:per_page] = params[:per_page]
end
if params[:all_names] == 'true'
@qparams[:all_names] = params[:all_names]
find_options[:include] = [:taxon_names]
if find_options[:conditions]
find_options[:conditions][0] += " OR #{TaxonName.table_name}.name LIKE ?"
find_options[:conditions] << ('%' + params[:q].split(' ').join('%') + '%')
else
find_options[:conditions] = [ "#{TaxonName.table_name}.name LIKE ?",
'%' + params[:q].split(' ').join('%') + '%' ]
end
end
@taxa = Taxon.paginate(find_options)
do_external_lookups
end
def retrieve_photos
[retrieve_remote_photos, retrieve_local_photos].flatten.compact
end
def retrieve_remote_photos
photo_classes = Photo.descendent_classes - [LocalPhoto]
photos = []
photo_classes.each do |photo_class|
param = photo_class.to_s.underscore.pluralize
next if params[param].blank?
params[param].reject {|i| i.blank?}.uniq.each do |photo_id|
if fp = photo_class.find_by_native_photo_id(photo_id)
photos << fp
else
pp = photo_class.get_api_response(photo_id)
photos << photo_class.new_from_api_response(pp)
end
end
end
photos
end
def retrieve_local_photos
return [] if params[:local_photos].nil?
photos = []
params[:local_photos].reject {|i| i.empty?}.uniq.each do |photo_id|
if fp = LocalPhoto.find_by_native_photo_id(photo_id)
photos << fp
end
end
photos
end
def load_taxon
unless @taxon = Taxon.find_by_id(params[:id].to_i, :include => :taxon_names)
render_404
return
end
end
def do_external_lookups
return unless logged_in?
return unless params[:force_external] || (params[:include_external] && @taxa.blank?)
@external_taxa = []
Rails.logger.info("DEBUG: Making an external lookup...")
begin
ext_names = TaxonName.find_external(params[:q], :src => params[:external_src])
rescue Timeout::Error, NameProviderError => e
@status = e.message
return
end
@external_taxa = Taxon.find(ext_names.map(&:taxon_id)) unless ext_names.blank?
return if @external_taxa.blank?
# graft in the background
@external_taxa.each do |external_taxon|
external_taxon.delay.graft_silently unless external_taxon.grafted?
end
@taxa = WillPaginate::Collection.create(1, @external_taxa.size) do |pager|
pager.replace(@external_taxa)
pager.total_entries = @external_taxa.size
end
end
def tag_flickr_photo(flickr_photo_id, tags, options = {})
flickr = options[:flickr] || get_flickraw
# Strip and enclose multiword tags in quotes
if tags.is_a?(Array)
tags = tags.map do |t|
t.strip.match(/\s+/) ? "\"#{t.strip}\"" : t.strip
end.join(' ')
end
begin
flickr.photos.addTags(:photo_id => flickr_photo_id, :tags => tags)
rescue FlickRaw::FailedResponse, FlickRaw::OAuthClient::FailedResponse => e
if e.message =~ /Insufficient permissions/ || e.message =~ /signature_invalid/
auth_url = auth_url_for('flickr', :scope => 'write')
flash[:error] = ("#{CONFIG.site_name_short} can't add tags to your photos until " +
"Flickr knows you've given us permission. " +
"<a href=\"#{auth_url}\">Click here to authorize #{CONFIG.site_name_short} to add tags</a>.").html_safe
else
flash[:error] = "Something went wrong trying to to post those tags: #{e.message}"
end
rescue Exception => e
flash[:error] = "Something went wrong trying to to post those tags: #{e.message}"
end
end
def presave
@taxon.photos = retrieve_photos
if params[:taxon_names]
TaxonName.update(params[:taxon_names].keys, params[:taxon_names].values)
end
if params[:taxon][:colors]
@taxon.colors = Color.find(params[:taxon].delete(:colors))
end
unless params[:taxon][:parent_id].blank?
unless Taxon.exists?(params[:taxon][:parent_id].to_i)
flash[:error] = "That parent taxon doesn't exist (try a different ID)"
render :action => 'edit'
return false
end
end
# Set the last editor
params[:taxon].update(:updater_id => current_user.id)
# Anyone who's allowed to create or update should be able to skip locks
params[:taxon].update(:skip_locks => true)
if params[:taxon][:featured_at] && params[:taxon][:featured_at] == "1"
params[:taxon][:featured_at] = Time.now
else
params[:taxon][:featured_at] = ""
end
true
end
def amphibiaweb_description?
params[:description] != 'wikipedia' && try_amphibiaweb?
end
def try_amphibiaweb?
@taxon.species_or_lower? &&
@taxon.ancestor_ids.include?(Taxon::ICONIC_TAXA_BY_NAME['Amphibia'].id)
end
# Temp method for fetching amphibiaweb desc. Will probably implement this
# through TaxonLinks eventually
def get_amphibiaweb(taxon_names)
taxon_name = taxon_names.pop
return unless taxon_name
@genus_name, @species_name = taxon_name.name.split
url = "http://amphibiaweb.org/cgi/amphib_ws?where-genus=#{@genus_name}&where-species=#{@species_name}&src=eol"
Rails.logger.info "[INFO #{Time.now}] AmphibiaWeb request: #{url}"
xml = Nokogiri::XML(open(url))
if xml.blank? || xml.at(:error)
get_amphibiaweb(taxon_names)
else
xml
end
end
def ensure_flickr_write_permission
@provider_authorization = current_user.provider_authorizations.first(:conditions => {:provider_name => 'flickr'})
if @provider_authorization.blank? || @provider_authorization.scope != 'write'
session[:return_to] = request.get? ? request.fullpath : request.env['HTTP_REFERER']
redirect_to auth_url_for('flickr', :scope => 'write')
return false
end
end
def load_single_taxon_map_data(taxon)
@taxon_range = taxon.taxon_ranges.without_geom.first
if params[:place_id] && (@place = Place.find_by_id(params[:place_id]))
@place_geometry = PlaceGeometry.without_geom.first(:conditions => {:place_id => @place.id})
end
@bounds = if @place && (bbox = @place.bounding_box)
GeoRuby::SimpleFeatures::Envelope.from_points([
Point.from_coordinates([bbox[1], bbox[0]]),
Point.from_coordinates([bbox[3], bbox[2]])
])
elsif @taxon_range
taxon.taxon_ranges.calculate(:extent, :geom)
else
Observation.of(taxon).calculate(:extent, :geom)
end
if @bounds
@extent = [
{:lon => @bounds.lower_corner.x, :lat => @bounds.lower_corner.y},
{:lon => @bounds.upper_corner.x, :lat => @bounds.upper_corner.y}
]
end
find_options = {
:select => "listed_taxa.id, place_id, last_observation_id, places.place_type, occurrence_status_level, establishment_means",
:joins => [:place],
:conditions => [
"place_id IS NOT NULL AND places.place_type = ?",
Place::PLACE_TYPE_CODES['County']
]
}
@county_listings = taxon.listed_taxa.all(find_options).index_by{|lt| lt.place_id}
find_options[:conditions][1] = Place::PLACE_TYPE_CODES['State']
@state_listings = taxon.listed_taxa.all(find_options).index_by{|lt| lt.place_id}
find_options[:conditions][1] = Place::PLACE_TYPE_CODES['Country']
@country_listings = taxon.listed_taxa.all(find_options).index_by{|lt| lt.place_id}
end
end
Bugfix: taxa/flickr_photos_tagged was bailing when passed invalid flickr ids.
#encoding: utf-8
class TaxaController < ApplicationController
caches_page :range, :if => Proc.new {|c| c.request.format == :geojson}
caches_action :show, :expires_in => 1.day, :if => Proc.new {|c|
c.session.blank? || c.session['warden.user.user.key'].blank?
}
caches_action :describe, :expires_in => 1.day, :if => Proc.new {|c|
c.session.blank? || c.session['warden.user.user.key'].blank?
}
include TaxaHelper
include Shared::WikipediaModule
before_filter :return_here, :only => [:index, :show, :flickr_tagger, :curation, :synonyms]
before_filter :authenticate_user!, :only => [:edit_photos, :update_photos,
:update_colors, :tag_flickr_photos, :tag_flickr_photos_from_observations,
:flickr_photos_tagged, :add_places, :synonyms]
before_filter :curator_required, :only => [:new, :create, :edit, :update,
:destroy, :curation, :refresh_wikipedia_summary, :merge, :synonyms]
before_filter :load_taxon, :only => [:edit, :update, :destroy, :photos,
:children, :graft, :describe, :edit_photos, :update_photos, :edit_colors,
:update_colors, :add_places, :refresh_wikipedia_summary, :merge,
:observation_photos, :range, :schemes, :tip]
before_filter :limit_page_param_for_thinking_sphinx, :only => [:index,
:browse, :search]
before_filter :ensure_flickr_write_permission, :only => [
:flickr_photos_tagged, :tag_flickr_photos,
:tag_flickr_photos_from_observations]
cache_sweeper :taxon_sweeper, :only => [:update, :destroy, :update_photos]
GRID_VIEW = "grid"
LIST_VIEW = "list"
BROWSE_VIEWS = [GRID_VIEW, LIST_VIEW]
ALLOWED_SHOW_PARTIALS = %w(chooser)
MOBILIZED = [:show, :index]
before_filter :unmobilized, :except => MOBILIZED
before_filter :mobilized, :only => MOBILIZED
#
# GET /observations
# GET /observations.xml
#
# @param name: Return all taxa where name is an EXACT match
# @param q: Return all taxa where the name begins with q
#
def index
find_taxa unless request.format == :html
begin
@taxa.try(:total_entries)
rescue ThinkingSphinx::SphinxError => e
Rails.logger.error "[ERROR #{Time.now}] Failed sphinx search: #{e}"
@taxa = WillPaginate::Collection.new(1,30,0)
end
respond_to do |format|
format.html do # index.html.erb
@featured_taxa = Taxon.all(:conditions => "featured_at IS NOT NULL",
:order => "featured_at DESC", :limit => 100,
:include => [:iconic_taxon, :photos, :taxon_names])
if @featured_taxa.blank?
@featured_taxa = Taxon.all(:limit => 100, :conditions => [
"taxa.wikipedia_summary IS NOT NULL AND " +
"photos.id IS NOT NULL AND " +
"taxa.observations_count > 1"
], :include => [:iconic_taxon, :photos, :taxon_names],
:order => "taxa.id DESC")
end
# Shuffle the taxa (http://snippets.dzone.com/posts/show/2994)
@featured_taxa = @featured_taxa.sort_by{rand}[0..10]
flash[:notice] = @status unless @status.blank?
if params[:q]
find_taxa
render :action => :search
else
@iconic_taxa = Taxon::ICONIC_TAXA
@recent = Observation.all(
:select => "DISTINCT ON (taxon_id) *",
:from => "(SELECT * from observations WHERE taxon_id IS NOT NULL ORDER BY observed_on DESC NULLS LAST LIMIT 10) AS obs",
:include => {:taxon => [:taxon_names]},
:limit => 5
).sort_by(&:id).reverse
end
end
format.mobile do
if @taxa.blank?
page = params[:page].to_i
page = 1 if page < 1
@taxon_photos = TaxonPhoto.paginate(:page => page, :per_page => 32, :order => "id DESC")
@taxa = Taxon.all(:conditions => ["id IN (?)", @taxon_photos.map{|tp| tp.taxon_id}])
end
end
format.xml do
render(:xml => @taxa.to_xml(
:include => :taxon_names, :methods => [:common_name]))
end
format.json do
@taxa = Taxon::ICONIC_TAXA if @taxa.blank? && params[:q].blank?
options = Taxon.default_json_options
options[:include].merge!(
:iconic_taxon => {:only => [:id, :name]},
:taxon_names => {:only => [:id, :name, :lexicon]}
)
options[:methods] += [:common_name, :image_url, :default_name]
render :json => @taxa.to_json(options)
end
end
end
def show
if params[:entry] == 'widget'
flash[:notice] = "Welcome to #{CONFIG.site_name_short}! Click 'Add an observtion' to the lower right. You'll be prompted to sign in/sign up if you haven't already"
end
@taxon ||= Taxon.find_by_id(params[:id].to_i, :include => [:taxon_names]) if params[:id]
return render_404 unless @taxon
if !@taxon.conservation_status.blank? && @taxon.conservation_status > Taxon::IUCN_LEAST_CONCERN
@conservation_status_name = @taxon.conservation_status_name
@conservation_status_source = @taxon.conservation_status_source
end
respond_to do |format|
format.html do
if @taxon.name == 'Life' && !@taxon.parent_id
return redirect_to(:action => 'index')
end
@amphibiaweb = amphibiaweb_description?
@try_amphibiaweb = try_amphibiaweb?
@children = @taxon.children.all(
:include => :taxon_names,
:conditions => {:is_active => @taxon.is_active}
).sort_by{|c| c.name}
@ancestors = @taxon.ancestors.all(:include => :taxon_names)
@iconic_taxa = Taxon::ICONIC_TAXA
@check_listed_taxa = ListedTaxon.page(1).
select("min(listed_taxa.id) AS id, listed_taxa.place_id, listed_taxa.taxon_id, min(listed_taxa.list_id) AS list_id, min(establishment_means) AS establishment_means").
includes(:place, :list).
group(:place_id, :taxon_id).
where("place_id IS NOT NULL AND taxon_id = ?", @taxon)
@sorted_check_listed_taxa = @check_listed_taxa.sort_by{|lt| lt.place.place_type || 0}.reverse
@places = @check_listed_taxa.map{|lt| lt.place}.uniq{|p| p.id}
@countries = @taxon.places.all(
:select => "places.id, place_type, code",
:conditions => ["place_type = ?", Place::PLACE_TYPE_CODES['Country']]
).uniq{|p| p.id}
if @countries.size == 1 && @countries.first.code == 'US'
@us_states = @taxon.places.all(
:select => "places.id, place_type, code",
:conditions => [
"place_type = ? AND parent_id = ?", Place::PLACE_TYPE_CODES['State'],
@countries.first.id
]
).uniq{|p| p.id}
end
@taxon_links = if @taxon.species_or_lower?
# fetch all relevant links
TaxonLink.for_taxon(@taxon).includes(:taxon)
else
# fetch links without species only
TaxonLink.for_taxon(@taxon).where(:species_only => false).includes(:taxon)
end
tl_place_ids = @taxon_links.map(&:place_id).compact
if !tl_place_ids.blank? # && !@places.blank?
if @places.blank?
@taxon_links.reject! {|tl| tl.place_id}
else
# fetch listed taxa for this taxon with places matching the links
place_listed_taxa = ListedTaxon.where("place_id IN (?)", tl_place_ids).where(:taxon_id => @taxon)
# remove links that have a place_id set but don't have a corresponding listed taxon
@taxon_links.reject! do |tl|
tl.place_id && place_listed_taxa.detect{|lt| lt.place_id == tl.place_id}.blank?
end
end
end
@taxon_links.uniq!{|tl| tl.url}
@taxon_links = @taxon_links.sort_by{|tl| tl.taxon.ancestry || ''}.reverse
@observations = Observation.of(@taxon).recently_added.all(:limit => 3)
@photos = Rails.cache.fetch(@taxon.photos_cache_key) do
@taxon.photos_with_backfill(:skip_external => true, :limit => 24)
end
if logged_in?
@listed_taxa = ListedTaxon.all(
:include => [:list],
:conditions => [
"lists.user_id = ? AND listed_taxa.taxon_id = ?",
current_user, @taxon
])
@listed_taxa_by_list_id = @listed_taxa.index_by{|lt| lt.list_id}
@current_user_lists = current_user.lists.includes(:rules)
@lists_rejecting_taxon = @current_user_lists.select do |list|
if list.is_a?(LifeList)
list.rules.map {|rule| rule.validates?(@taxon)}.include?(false)
else
false
end
end
end
@taxon_range = @taxon.taxon_ranges.without_geom.first
@taxon_gbif = "#{@taxon.name.gsub(' ','+')}*"
@show_range = @taxon_range
@colors = @taxon.colors if @taxon.species_or_lower?
unless @taxon.is_active?
@taxon_change = TaxonChange.taxon(@taxon).last
end
render :action => 'show'
end
format.mobile do
if @taxon.species_or_lower? && @taxon.species
@siblings = @taxon.species.siblings.all(:limit => 100, :include => [:photos, :taxon_names]).sort_by{|t| t.name}
@siblings.delete_if{|s| s.id == @taxon.id}
else
@children = @taxon.children.all(:limit => 100, :include => [:photos, :taxon_names]).sort_by{|t| t.name}
end
end
format.xml do
render :xml => @taxon.to_xml(
:include => [:taxon_names, :iconic_taxon],
:methods => [:common_name]
)
end
format.json do
if (partial = params[:partial]) && ALLOWED_SHOW_PARTIALS.include?(partial)
@taxon.html = render_to_string(:partial => "#{partial}.html.erb", :object => @taxon)
end
render(:json => @taxon.to_json(
:include => [:taxon_names, :iconic_taxon],
:methods => [:common_name, :image_url, :html])
)
end
format.node { render :json => jit_taxon_node(@taxon) }
end
end
def tip
@observation = Observation.find_by_id(params[:observation_id]) if params[:observation_id]
if @observation
@places = @observation.system_places
end
render :layout => false
end
def new
@taxon = Taxon.new(:name => params[:name])
end
def create
@taxon = Taxon.new
return unless presave
@taxon.attributes = params[:taxon]
@taxon.creator = current_user
if @taxon.save
flash[:notice] = 'Taxon was successfully created.'
if locked_ancestor = @taxon.ancestors.is_locked.first
flash[:notice] += " Heads up: you just added a descendant of a " +
"locked taxon (<a href='/taxa/#{locked_ancestor.id}'>" +
"#{locked_ancestor.name}</a>). Please consider merging this " +
"into an existing taxon instead."
end
redirect_to :action => 'show', :id => @taxon
else
render :action => 'new'
end
end
def edit
descendant_options = {:joins => [:taxon], :conditions => @taxon.descendant_conditions}
taxon_options = {:conditions => {:taxon_id => @taxon}}
@observations_exist = Observation.first(taxon_options) || Observation.first(descendant_options)
@listed_taxa_exist = ListedTaxon.first(taxon_options) || ListedTaxon.first(descendant_options)
@identifications_exist = Identification.first(taxon_options) || Identification.first(descendant_options)
@descendants_exist = @taxon.descendants.first
@taxon_range = TaxonRange.without_geom.first(:conditions => {:taxon_id => @taxon})
end
def update
return unless presave
if @taxon.update_attributes(params[:taxon])
flash[:notice] = 'Taxon was successfully updated.'
if locked_ancestor = @taxon.ancestors.is_locked.first
flash[:notice] += " Heads up: you just added a descendant of a " +
"locked taxon (<a href='/taxa/#{locked_ancestor.id}'>" +
"#{locked_ancestor.name}</a>). Please consider merging this " +
"into an existing taxon instead."
end
redirect_to taxon_path(@taxon)
return
else
render :action => 'edit'
end
end
def destroy
@taxon.destroy
flash[:notice] = "Taxon deleted."
redirect_to :action => 'index'
end
## Custom actions ############################################################
# /taxa/browse?q=bird
# /taxa/browse?q=bird&places=1,2&colors=4,5
# TODO: /taxa/browse?q=bird&places=usa-ca-berkeley,usa-ct-clinton&colors=blue,black
def search
@q = params[:q] = params[:q].to_s.sanitize_encoding
match_mode = :all
# Wrap the query in modifiers to ensure exact matches show first
if @q.blank?
q = @q
else
q = sanitize_sphinx_query(@q)
# for some reason 1-term queries don't return an exact match first if enclosed
# in quotes, so we only use them for multi-term queries
q = if q =~ /\s/
"\"^#{q}$\" | #{q}"
else
"^#{q}$ | #{q}"
end
match_mode = :extended
end
drill_params = {}
if params[:taxon_id] && (@taxon = Taxon.find_by_id(params[:taxon_id].to_i))
drill_params[:ancestors] = @taxon.id
end
if params[:is_active] == "true" || params[:is_active].blank?
@is_active = true
drill_params[:is_active] = true
elsif params[:is_active] == "false"
@is_active = false
drill_params[:is_active] = false
else
@is_active = params[:is_active]
end
if params[:iconic_taxa] && @iconic_taxa_ids = params[:iconic_taxa].split(',')
@iconic_taxa_ids = @iconic_taxa_ids.map(&:to_i)
@iconic_taxa = Taxon.find(@iconic_taxa_ids)
drill_params[:iconic_taxon_id] = @iconic_taxa_ids
end
# if params[:places] && @place_ids = params[:places].split(',')
# @place_ids = @place_ids.map(&:to_i)
# @places = Place.find(@place_ids)
# drill_params[:places] = @place_ids
# end
if params[:colors] && @color_ids = params[:colors].split(',')
@color_ids = @color_ids.map(&:to_i)
@colors = Color.find(@color_ids)
drill_params[:colors] = @color_ids
end
per_page = params[:per_page] ? params[:per_page].to_i : 24
per_page = 100 if per_page > 100
page = params[:page] ? params[:page].to_i : 1
@facets = Taxon.facets(q, :page => page, :per_page => per_page,
:with => drill_params,
:include => [:taxon_names, :photos],
:field_weights => {:name => 2},
:match_mode => match_mode)
if @facets[:iconic_taxon_id]
@faceted_iconic_taxa = Taxon.all(
:conditions => ["id in (?)", @facets[:iconic_taxon_id].keys],
:include => [:taxon_names, :photos]
)
@faceted_iconic_taxa = Taxon.sort_by_ancestry(@faceted_iconic_taxa)
@faceted_iconic_taxa_by_id = @faceted_iconic_taxa.index_by(&:id)
end
if @facets[:colors]
@faceted_colors = Color.all(:conditions => ["id in (?)", @facets[:colors].keys])
@faceted_colors_by_id = @faceted_colors.index_by(&:id)
end
@taxa = @facets.for(drill_params)
begin
@taxa.blank?
rescue ThinkingSphinx::SphinxError, Riddle::OutOfBoundsError => e
Rails.logger.error "[ERROR #{Time.now}] Failed sphinx search: #{e}"
@taxa = WillPaginate::Collection.new(1,30,0)
end
do_external_lookups
unless @taxa.blank?
# if there's an exact match among the hits, make sure it's first
if exact_index = @taxa.index{|t| t.all_names.map(&:downcase).include?(params[:q].to_s.downcase)}
if exact_index > 0
@taxa.unshift @taxa.delete_at(exact_index)
end
# otherwise try and hit the db directly. Sphinx doesn't always seem to behave properly
elsif params[:page].to_i <= 1 && (exact = Taxon.where("lower(name) = ?", params[:q].to_s.downcase.strip).first)
@taxa.unshift exact
end
end
respond_to do |format|
format.html do
@view = BROWSE_VIEWS.include?(params[:view]) ? params[:view] : GRID_VIEW
flash[:notice] = @status unless @status.blank?
if @taxa.blank?
@all_iconic_taxa = Taxon::ICONIC_TAXA
@all_colors = Color.all
end
if params[:partial]
render :partial => "taxa/#{params[:partial]}.html.erb", :locals => {
:js_link => params[:js_link]
}
else
render :browse
end
end
format.json do
options = Taxon.default_json_options
options[:include].merge!(
:iconic_taxon => {:only => [:id, :name]},
:taxon_names => {:only => [:id, :name, :lexicon, :is_valid]}
)
options[:methods] += [:common_name, :image_url, :default_name]
render :json => @taxa.to_json(options)
end
end
end
def autocomplete
@q = params[:q] || params[:term]
@is_active = if params[:is_active] == "true" || params[:is_active].blank?
true
elsif params[:is_active] == "false"
false
else
params[:is_active]
end
scope = TaxonName.includes(:taxon => :taxon_names).
where("lower(taxon_names.name) LIKE ?", "#{@q.to_s.downcase}%").
limit(30).scoped
scope = scope.where("taxa.is_active = ?", @is_active) unless @is_active == "any"
@taxon_names = scope.sort_by{|tn| tn.taxon.ancestry || ''}
exact_matches = []
@taxon_names.each_with_index do |taxon_name, i|
next unless taxon_name.name.downcase.strip == @q.to_s.downcase.strip
exact_matches << @taxon_names.delete_at(i)
end
if exact_matches.blank?
exact_matches = TaxonName.all(:include => {:taxon => :taxon_names},
:conditions => ["lower(taxon_names.name) = ?", @q.to_s.downcase])
end
@taxon_names = exact_matches + @taxon_names
@taxa = @taxon_names.map do |taxon_name|
taxon = taxon_name.taxon
taxon.html = view_context.render_in_format(:html, :partial => "chooser.html.erb",
:object => taxon, :comname => taxon_name.is_scientific_names? ? nil : taxon_name)
taxon
end
respond_to do |format|
format.json do
render :json => @taxa.to_json(:methods => [:html])
end
end
end
def browse
redirect_to :action => "search"
end
def occur_in
@taxa = Taxon.occurs_in(params[:swlng], params[:swlat], params[:nelng],
params[:nelat], params[:startDate], params[:endDate])
@taxa.sort! do |a,b|
(a.common_name ? a.common_name.name : a.name) <=> (b.common_name ? b.common_name.name : b.name)
end
respond_to do |format|
format.html
format.json do
render :text => @taxa.to_json(
:methods => [:id, :common_name] )
end
end
end
#
# List child taxa of this taxon
#
def children
respond_to do |format|
format.html { redirect_to taxon_path(@taxon) }
format.xml do
render :xml => @taxon.children.to_xml(
:include => :taxon_names, :methods => [:common_name] )
end
format.json do
options = Taxon.default_json_options
options[:include].merge!(:taxon_names => {:only => [:id, :name, :lexicon]})
options[:methods] += [:common_name]
render :json => @taxon.children.all(:include => [{:taxon_photos => :photo}, :taxon_names]).to_json(options)
end
end
end
def photos
limit = params[:limit].to_i
limit = 24 if limit.blank? || limit == 0
limit = 50 if limit > 50
begin
@photos = Rails.cache.fetch(@taxon.photos_with_external_cache_key) do
@taxon.photos_with_backfill(:limit => 50).map do |fp|
fp.api_response = nil
fp
end
end[0..(limit-1)]
rescue Timeout::Error => e
Rails.logger.error "[ERROR #{Time.now}] Timeout: #{e}"
@photos = @taxon.photos
end
if params[:partial]
key = {:controller => 'taxa', :action => 'photos', :id => @taxon.id, :partial => params[:partial]}
if fragment_exist?(key)
content = read_fragment(key)
else
content = if @photos.blank?
'<div class="description">No matching photos.</div>'
else
render_to_string :partial => "taxa/#{params[:partial]}", :collection => @photos
end
write_fragment(key, content)
end
render :layout => false, :text => content
else
render :layout => false, :partial => "photos", :locals => {
:photos => @photos
}
end
rescue SocketError => e
raise unless Rails.env.development?
Rails.logger.debug "[DEBUG] Looks like you're offline, skipping flickr"
render :text => "You're offline."
end
def schemes
@scheme_taxa = TaxonSchemeTaxon.all(:conditions => {:taxon_id => @taxon.id})
end
def map
@cloudmade_key = CONFIG.cloudmade.key
@bing_key = CONFIG.bing.key
if @taxon = Taxon.find_by_id(params[:id].to_i)
load_single_taxon_map_data(@taxon)
end
taxon_ids = if params[:taxa].is_a?(Array)
params[:taxa]
elsif params[:taxa].is_a?(String)
params[:taxa].split(',')
end
if taxon_ids
@taxa = Taxon.all(:conditions => ["id IN (?)", taxon_ids.map{|t| t.to_i}], :limit => 20)
@taxon_ranges = TaxonRange.without_geom.all(:conditions => ["taxon_id IN (?)", @taxa]).group_by(&:taxon_id)
@taxa_data = taxon_ids.map do |taxon_id|
next unless taxon = @taxa.detect{|t| t.id == taxon_id.to_i}
taxon.as_json(:only => [:id, :name, :is_active]).merge(
:range_url => @taxon_ranges[taxon.id] ? taxon_range_geom_url(taxon.id, :format => "geojson") : nil,
:observations_url => taxon.observations.exists? ? observations_of_url(taxon, :format => "geojson") : nil,
)
end
@bounds = if !@taxon_ranges.blank?
TaxonRange.calculate(:extent, :geom, :conditions => ["taxon_id IN (?)", @taxa])
else
Observation.of(@taxa.first).calculate(:extent, :geom)
end
if @bounds
@extent = [
{:lon => @bounds.lower_corner.x, :lat => @bounds.lower_corner.y},
{:lon => @bounds.upper_corner.x, :lat => @bounds.upper_corner.y}
]
end
end
if params[:test]
@child_taxa = @taxon.descendants.of_rank(Taxon::SPECIES).all(:limit => 10)
@child_taxon_ranges = TaxonRange.without_geom.all(:conditions => ["taxon_id IN (?)", @child_taxa]).group_by(&:taxon_id)
@children = @child_taxa.map do |child|
{
:id => child.id,
:range_url => @child_taxon_ranges[child.id] ? taxon_range_geom_url(child.id, :format => "geojson") : nil,
:observations_url => observations_of_url(child, :format => "geojson"),
:name => child.name
}
end
end
end
def range
@taxon_range = if request.format == :geojson
@taxon.taxon_ranges.simplified.first
else
@taxon.taxon_ranges.first
end
unless @taxon_range
flash[:error] = "Taxon doesn't have a range"
redirect_to @taxon
return
end
respond_to do |format|
format.html { redirect_to taxon_map_path(@taxon) }
format.kml { redirect_to @taxon_range.range.url }
format.geojson { render :json => [@taxon_range].to_geojson }
end
end
def observation_photos
if per_page = params[:per_page]
per_page = per_page.to_i > 50 ? 50 : per_page.to_i
end
observations = if params[:q].blank?
Observation.of(@taxon).paginate(:page => params[:page],
:per_page => per_page, :include => [:photos],
:conditions => "photos.id IS NOT NULL")
else
Observation.search(params[:q], :page => params[:page],
:per_page => per_page, :with => {:has_photos => true, :taxon_id => @taxon.id})
end
@photos = observations.map(&:photos).flatten
render :partial => 'photos/photo_list_form', :locals => {
:photos => @photos,
:index => params[:index],
:local_photos => false }
end
def edit_photos
render :layout => false
end
def add_places
unless params[:tab].blank?
@places = case params[:tab]
when 'countries'
@countries = Place.all(:order => "name",
:conditions => ["place_type = ?", Place::PLACE_TYPE_CODES["Country"]]).compact
when 'us_states'
if @us = Place.find_by_name("United States")
@us.children.all(:order => "name").compact
else
[]
end
else
[]
end
@listed_taxa = @taxon.listed_taxa.all(:conditions => ["place_id IN (?)", @places],
:select => "DISTINCT ON (place_id) listed_taxa.*")
@listed_taxa_by_place_id = @listed_taxa.index_by(&:place_id)
render :partial => 'taxa/add_to_place_link', :collection => @places, :locals => {
:skip_map => true
}
return
end
if request.post?
if params[:paste_places]
add_places_from_paste
else
add_places_from_search
end
respond_to do |format|
format.json do
@places.each_with_index do |place, i|
@places[i].html = view_context.render_in_format(:html, :partial => 'add_to_place_link', :object => place)
end
render :json => @places.to_json(:methods => [:html])
end
end
return
end
render :layout => false
end
private
def add_places_from_paste
place_names = params[:paste_places].split(",").map{|p| p.strip.downcase}.reject(&:blank?)
@places = Place.all(:conditions => [
"place_type = ? AND name IN (?)",
Place::PLACE_TYPE_CODES['Country'], place_names
])
@places ||= []
(place_names - @places.map{|p| p.name.strip.downcase}).each do |new_place_name|
ydn_places = GeoPlanet::Place.search(new_place_name, :count => 1, :type => "Country")
next if ydn_places.blank?
@places << Place.import_by_woeid(ydn_places.first.woeid)
end
@listed_taxa = @places.map do |place|
place.check_list.try(:add_taxon, @taxon, :user_id => current_user.id)
end.select{|p| p.valid?}
@listed_taxa_by_place_id = @listed_taxa.index_by{|lt| lt.place_id}
end
def add_places_from_search
search_for_places
@listed_taxa = @taxon.listed_taxa.all(:conditions => ["place_id IN (?)", @places],
:select => "DISTINCT ON (place_id) listed_taxa.*")
@listed_taxa_by_place_id = @listed_taxa.index_by(&:place_id)
end
public
def find_places
@limit = 5
@js_link = params[:js_link]
@partial = params[:partial]
search_for_places
render :layout => false
end
def update_photos
photos = retrieve_photos
errors = photos.map do |p|
p.valid? ? nil : p.errors.full_messages
end.flatten.compact
@taxon.photos = photos
@taxon.save
unless photos.count == 0
Taxon.delay(:priority => INTEGRITY_PRIORITY).update_ancestor_photos(@taxon.id, photos.first.id)
end
if errors.blank?
flash[:notice] = "Taxon photos updated!"
else
flash[:error] = "Some of those photos couldn't be saved: #{errors.to_sentence.downcase}"
end
redirect_to taxon_path(@taxon)
rescue Errno::ETIMEDOUT
flash[:error] = "Request timed out!"
redirect_back_or_default(taxon_path(@taxon))
rescue Koala::Facebook::APIError => e
raise e unless e.message =~ /OAuthException/
flash[:error] = "Facebook needs the owner of that photo to re-confirm their connection to #{CONFIG.site_name_short}."
redirect_back_or_default(taxon_path(@taxon))
end
def describe
@amphibiaweb = amphibiaweb_description?
if @amphibiaweb
taxon_names = @taxon.taxon_names.all(
:conditions => {:lexicon => TaxonName::LEXICONS[:SCIENTIFIC_NAMES]},
:order => "is_valid, id desc")
if @xml = get_amphibiaweb(taxon_names)
render :partial => "amphibiaweb"
return
else
@before_wikipedia = '<div class="notice status">AmphibiaWeb didn\'t have info on this taxon, showing Wikipedia instead.</div>'
end
end
@title = @taxon.wikipedia_title.blank? ? @taxon.name : @taxon.wikipedia_title
wikipedia
end
def refresh_wikipedia_summary
begin
summary = @taxon.set_wikipedia_summary
rescue Timeout::Error => e
error_text = e.message
end
if summary.blank?
error_text ||= "Could't retrieve the Wikipedia " +
"summary for #{@taxon.name}. Make sure there is actually a " +
"corresponding article on Wikipedia."
render :status => 404, :text => error_text
else
render :text => summary
end
end
def update_colors
unless params[:taxon] && params[:taxon][:color_ids]
redirect_to @taxon
end
params[:taxon][:color_ids].delete_if(&:blank?)
@taxon.colors = Color.find(params[:taxon].delete(:color_ids))
respond_to do |format|
if @taxon.save
format.html { redirect_to @taxon }
format.json do
render :json => @taxon
end
else
msg = "There were some problems saving those colors: #{@taxon.errors.full_messages.join(', ')}"
format.html do
flash[:error] = msg
redirect_to @taxon
end
format.json do
render :json => {:errors => msg}, :status => :unprocessable_entity
end
end
end
end
def graft
begin
lineage = ratatosk.graft(@taxon)
rescue Timeout::Error => e
@error_message = e.message
rescue RatatoskGraftError => e
@error_message = e.message
end
@taxon.reload
@error_message ||= "Graft failed. Please graft manually by editing the taxon." unless @taxon.grafted?
respond_to do |format|
format.html do
flash[:error] = @error_message if @error_message
redirect_to(edit_taxon_path(@taxon))
end
format.js do
if @error_message
render :status => :unprocessable_entity, :text => @error_message
else
render :text => "Taxon grafted to #{@taxon.parent.name}"
end
end
format.json do
if @error_message
render :status => :unprocessable_entity, :json => {:error => @error_message}
else
render :json => {:msg => "Taxon grafted to #{@taxon.parent.name}"}
end
end
end
end
def merge
@keeper = Taxon.find_by_id(params[:taxon_id].to_i)
if @keeper && @keeper.id == @taxon.id
msg = "Failed to merge taxon #{@taxon.id} (#{@taxon.name}) into taxon #{@keeper.id} (#{@keeper.name}). You can't merge a taxon with itself."
respond_to do |format|
format.html do
flash[:error] = msg
redirect_back_or_default(@taxon)
return
end
format.js do
render :text => msg, :status => :unprocessable_entity, :layout => false
return
end
format.json { render :json => {:error => msg} }
end
end
if request.post? && @keeper
if @taxon.id == @keeper_id
flash[:error] = "Can't merge a taxon with itself."
return redirect_to :action => "merge", :id => @taxon
end
@keeper.merge(@taxon)
flash[:notice] = "#{@taxon.name} (#{@taxon.id}) merged into " +
"#{@keeper.name} (#{@keeper.id}). #{@taxon.name} (#{@taxon.id}) " +
"has been deleted."
respond_to do |format|
format.html do
if session[:return_to].to_s =~ /#{@taxon.id}/
redirect_to @keeper
else
redirect_back_or_default(@keeper)
end
end
format.json { render :json => @keeper }
end
return
end
respond_to do |format|
format.html
format.js do
@taxon_change = TaxonChange.input_taxon(@taxon).output_taxon(@keeper).first
@taxon_change ||= TaxonChange.input_taxon(@keeper).output_taxon(@taxon).first
render :partial => "taxa/merge"
end
format.json { render :json => @keeper }
end
end
def curation
@flags = Flag.paginate(:page => params[:page],
:include => :user,
:conditions => "resolved = false AND flaggable_type = 'Taxon'",
:order => "flags.id desc")
@resolved_flags = Flag.all(:limit => 5,
:include => [:user, :resolver],
:conditions => "resolved = true AND flaggable_type = 'Taxon'",
:order => "flags.id desc")
life = Taxon.find_by_name('Life')
@ungrafted = Taxon.roots.active.paginate(:conditions => ["id != ?", life],
:page => 1, :per_page => 100, :include => [:taxon_names])
end
def synonyms
filters = params[:filters] || {}
@iconic_taxon = filters[:iconic_taxon]
@rank = filters[:rank]
scope = Taxon.active.scoped
scope = scope.self_and_descendants_of(@iconic_taxon) unless @iconic_taxon.blank?
scope = scope.of_rank(@rank) unless @rank.blank?
@taxa = scope.paginate(
:page => params[:page],
:per_page => 100,
:order => "rank_level",
:joins => "LEFT OUTER JOIN taxa t ON t.name = taxa.name",
:conditions => ["t.id IS NOT NULL AND t.id != taxa.id AND t.is_active = ?", true]
)
@synonyms = Taxon.active.all(
:conditions => ["name IN (?)", @taxa.map{|t| t.name}],
:include => [:taxon_names, :taxon_schemes]
)
@synonyms_by_name = @synonyms.group_by{|t| t.name}
end
def flickr_tagger
f = get_flickraw
@taxon ||= Taxon.find_by_id(params[:id].to_i) if params[:id]
@taxon ||= Taxon.find_by_id(params[:taxon_id].to_i) if params[:taxon_id]
@flickr_photo_ids = [params[:flickr_photo_id], params[:flickr_photos]].flatten.compact
@flickr_photos = @flickr_photo_ids.map do |flickr_photo_id|
begin
original = f.photos.getInfo(:photo_id => flickr_photo_id)
flickr_photo = FlickrPhoto.new_from_api_response(original)
if flickr_photo && @taxon.blank?
if @taxa = flickr_photo.to_taxa
@taxon = @taxa.sort_by{|t| t.ancestry || ''}.last
end
end
flickr_photo
rescue FlickRaw::FailedResponse => e
flash[:notice] = "Sorry, one of those Flickr photos either doesn't exist or " +
"you don't have permission to view it."
nil
end
end.compact
@tags = @taxon ? @taxon.to_tags : []
respond_to do |format|
format.html
format.json { render :json => @tags}
end
end
def tag_flickr_photos
# Post tags to flickr
if params[:flickr_photos].blank?
flash[:notice] = "You didn't select any photos to tag!"
redirect_to :action => 'flickr_tagger' and return
end
unless logged_in? && current_user.flickr_identity
flash[:notice] = "Sorry, you need to be signed in and have a " +
"linked Flickr account to post tags directly to Flickr."
redirect_to :action => 'flickr_tagger' and return
end
flickr = get_flickraw
photos = FlickrPhoto.all(:conditions => ["native_photo_id IN (?)", params[:flickr_photos]], :include => :observations)
params[:flickr_photos].each do |flickr_photo_id|
tags = params[:tags]
photo = nil
if photo = photos.detect{|p| p.native_photo_id == flickr_photo_id}
tags += " " + photo.observations.map{|o| "inaturalist:observation=#{o.id}"}.join(' ')
tags.strip!
end
tag_flickr_photo(flickr_photo_id, tags, :flickr => flickr)
return redirect_to :action => "flickr_tagger" unless flash[:error].blank?
end
flash[:notice] = "Your photos have been tagged!"
redirect_to :action => 'flickr_photos_tagged',
:flickr_photos => params[:flickr_photos], :tags => params[:tags]
end
def tag_flickr_photos_from_observations
if params[:o].blank?
flash[:error] = "You didn't select any observations."
return redirect_to :back
end
@observations = current_user.observations.all(
:conditions => ["id IN (?)", params[:o].split(',')],
:include => [:photos, {:taxon => :taxon_names}]
)
if @observations.blank?
flash[:error] = "No observations matching those IDs."
return redirect_to :back
end
if @observations.map(&:user_id).uniq.size > 1 || @observations.first.user_id != current_user.id
flash[:error] = "You don't have permission to edit those photos."
return redirect_to :back
end
flickr = get_flickraw
flickr_photo_ids = []
@observations.each do |observation|
observation.photos.each do |photo|
next unless photo.is_a?(FlickrPhoto)
next unless observation.taxon
tags = observation.taxon.to_tags
tags << "inaturalist:observation=#{observation.id}"
tag_flickr_photo(photo.native_photo_id, tags, :flickr => flickr)
unless flash[:error].blank?
return redirect_to :back
end
flickr_photo_ids << photo.native_photo_id
end
end
redirect_to :action => 'flickr_photos_tagged', :flickr_photos => flickr_photo_ids
end
def flickr_photos_tagged
flickr = get_flickraw
@tags = params[:tags]
if params[:flickr_photos].blank?
flash[:error] = "No Flickr photos tagged!"
return redirect_to :action => "flickr_tagger"
end
@flickr_photos = params[:flickr_photos].map do |flickr_photo_id|
begin
fp = flickr.photos.getInfo(:photo_id => flickr_photo_id)
FlickrPhoto.new_from_flickraw(fp, :user => current_user)
rescue FlickRaw::FailedResponse => e
nil
end
end.compact
@observations = current_user.observations.all(
:include => :photos,
:conditions => [
"photos.native_photo_id IN (?) AND photos.type = ?",
@flickr_photos.map(&:native_photo_id), FlickrPhoto.to_s
]
)
@observations_by_native_photo_id = {}
@observations.each do |observation|
observation.photos.each do |flickr_photo|
@observations_by_native_photo_id[flickr_photo.native_photo_id] = observation
end
end
end
def tree
@taxon = Taxon.find_by_id(params[:id], :include => [:taxon_names, :photos])
@taxon ||= Taxon.find_by_id(params[:taxon_id].to_i, :include => [:taxon_names, :photos])
unless @taxon
@taxon = Taxon.find_by_name('Life')
@taxon ||= Taxon.iconic_taxa.first.parent
end
@iconic_taxa = Taxon::ICONIC_TAXA
end
# Try to find a taxon from urls like /taxa/Animalia or /taxa/Homo_sapiens
def try_show
name, format = params[:q].to_s.sanitize_encoding.split('_').join(' ').split('.')
request.format = format if request.format.blank? && !format.blank?
name = name.to_s.downcase
# Try to look by its current unique name
unless @taxon
begin
taxa = Taxon.all(:conditions => ["unique_name = ?", name], :limit => 2) unless @taxon
rescue ActiveRecord::StatementInvalid, PGError => e
raise e unless e.message =~ /invalid byte sequence/ || e.message =~ /incomplete multibyte character/
name = name.encode('UTF-8')
taxa = Taxon.all(:conditions => ["unique_name = ?", name], :limit => 2)
end
@taxon = taxa.first if taxa.size == 1
end
# Try to look by its current scientifc name
unless @taxon
begin
taxa = Taxon.all(:conditions => ["lower(name) = ?", name], :limit => 2) unless @taxon
rescue ActiveRecord::StatementInvalid => e
raise e unless e.message =~ /invalid byte sequence/
name = name.encode('UTF-8')
taxa = Taxon.all(:conditions => ["lower(name) = ?", name], :limit => 2)
end
@taxon = taxa.first if taxa.size == 1
end
# Try to find a unique TaxonName
unless @taxon
begin
taxon_names = TaxonName.all(:conditions => ["lower(name) = ?", name], :limit => 2)
rescue ActiveRecord::StatementInvalid => e
raise e unless e.message =~ /invalid byte sequence/
name = name.encode('UTF-8')
taxon_names = TaxonName.all(:conditions => ["lower(name) = ?", name], :limit => 2)
end
if taxon_names.size == 1
@taxon = taxon_names.first.taxon
# Redirect to the currently accepted sciname if this isn't an accepted sciname
unless taxon_names.first.is_valid?
return redirect_to :action => @taxon.name.split.join('_')
end
end
end
# Redirect to a canonical form
if @taxon
canonical = (@taxon.unique_name || @taxon.name).split.join('_')
taxon_names ||= @taxon.taxon_names.all
acceptable_names = [@taxon.unique_name, @taxon.name].compact.map{|n| n.split.join('_')} +
taxon_names.map{|tn| tn.name.split.join('_')}
unless acceptable_names.include?(params[:q])
redirect_target = if params[:action].to_s.split.join('_') == @taxon.name.split.join('_')
@taxon.name.split.join('_')
else
canonical
end
return redirect_to :action => redirect_target
end
end
# TODO: if multiple exact matches, render a disambig page with status 300 (Mulitple choices)
unless @taxon
return redirect_to :action => 'search', :q => name
else
params.delete(:q)
return_here
show
end
end
## Protected / private actions ###############################################
private
def find_taxa
find_options = {
:order => "#{Taxon.table_name}.name ASC",
:include => :taxon_names
}
@qparams = {}
if params[:q]
@qparams[:q] = params[:q]
find_options[:conditions] = [ "#{Taxon.table_name}.name LIKE ?",
'%' + params[:q].split(' ').join('%') + '%' ]
elsif params[:name]
@qparams[:name] = params[:name]
find_options[:conditions] = [ "name = ?", params[:name] ]
elsif params[:names]
names = if params[:names].is_a?(String)
params[:names].split(',')
else
params[:names]
end
taxon_names = TaxonName.where("name IN (?)", names).limit(100)
find_options[:conditions] = ["taxa.is_active = ? AND taxa.id IN (?)", true, taxon_names.map(&:taxon_id).uniq]
else
find_options[:conditions] = ["is_iconic = ?", true]
find_options[:order] = :ancestry
end
if params[:limit]
@qparams[:limit] = params[:limit]
find_options[:limit] = params[:limit]
else
find_options[:page] = params[:page] || 1
find_options[:per_page] = params[:per_page]
end
if params[:all_names] == 'true'
@qparams[:all_names] = params[:all_names]
find_options[:include] = [:taxon_names]
if find_options[:conditions]
find_options[:conditions][0] += " OR #{TaxonName.table_name}.name LIKE ?"
find_options[:conditions] << ('%' + params[:q].split(' ').join('%') + '%')
else
find_options[:conditions] = [ "#{TaxonName.table_name}.name LIKE ?",
'%' + params[:q].split(' ').join('%') + '%' ]
end
end
@taxa = Taxon.paginate(find_options)
do_external_lookups
end
def retrieve_photos
[retrieve_remote_photos, retrieve_local_photos].flatten.compact
end
def retrieve_remote_photos
photo_classes = Photo.descendent_classes - [LocalPhoto]
photos = []
photo_classes.each do |photo_class|
param = photo_class.to_s.underscore.pluralize
next if params[param].blank?
params[param].reject {|i| i.blank?}.uniq.each do |photo_id|
if fp = photo_class.find_by_native_photo_id(photo_id)
photos << fp
else
pp = photo_class.get_api_response(photo_id)
photos << photo_class.new_from_api_response(pp)
end
end
end
photos
end
def retrieve_local_photos
return [] if params[:local_photos].nil?
photos = []
params[:local_photos].reject {|i| i.empty?}.uniq.each do |photo_id|
if fp = LocalPhoto.find_by_native_photo_id(photo_id)
photos << fp
end
end
photos
end
def load_taxon
unless @taxon = Taxon.find_by_id(params[:id].to_i, :include => :taxon_names)
render_404
return
end
end
def do_external_lookups
return unless logged_in?
return unless params[:force_external] || (params[:include_external] && @taxa.blank?)
@external_taxa = []
Rails.logger.info("DEBUG: Making an external lookup...")
begin
ext_names = TaxonName.find_external(params[:q], :src => params[:external_src])
rescue Timeout::Error, NameProviderError => e
@status = e.message
return
end
@external_taxa = Taxon.find(ext_names.map(&:taxon_id)) unless ext_names.blank?
return if @external_taxa.blank?
# graft in the background
@external_taxa.each do |external_taxon|
external_taxon.delay.graft_silently unless external_taxon.grafted?
end
@taxa = WillPaginate::Collection.create(1, @external_taxa.size) do |pager|
pager.replace(@external_taxa)
pager.total_entries = @external_taxa.size
end
end
def tag_flickr_photo(flickr_photo_id, tags, options = {})
flickr = options[:flickr] || get_flickraw
# Strip and enclose multiword tags in quotes
if tags.is_a?(Array)
tags = tags.map do |t|
t.strip.match(/\s+/) ? "\"#{t.strip}\"" : t.strip
end.join(' ')
end
begin
flickr.photos.addTags(:photo_id => flickr_photo_id, :tags => tags)
rescue FlickRaw::FailedResponse, FlickRaw::OAuthClient::FailedResponse => e
if e.message =~ /Insufficient permissions/ || e.message =~ /signature_invalid/
auth_url = auth_url_for('flickr', :scope => 'write')
flash[:error] = ("#{CONFIG.site_name_short} can't add tags to your photos until " +
"Flickr knows you've given us permission. " +
"<a href=\"#{auth_url}\">Click here to authorize #{CONFIG.site_name_short} to add tags</a>.").html_safe
else
flash[:error] = "Something went wrong trying to to post those tags: #{e.message}"
end
rescue Exception => e
flash[:error] = "Something went wrong trying to to post those tags: #{e.message}"
end
end
def presave
@taxon.photos = retrieve_photos
if params[:taxon_names]
TaxonName.update(params[:taxon_names].keys, params[:taxon_names].values)
end
if params[:taxon][:colors]
@taxon.colors = Color.find(params[:taxon].delete(:colors))
end
unless params[:taxon][:parent_id].blank?
unless Taxon.exists?(params[:taxon][:parent_id].to_i)
flash[:error] = "That parent taxon doesn't exist (try a different ID)"
render :action => 'edit'
return false
end
end
# Set the last editor
params[:taxon].update(:updater_id => current_user.id)
# Anyone who's allowed to create or update should be able to skip locks
params[:taxon].update(:skip_locks => true)
if params[:taxon][:featured_at] && params[:taxon][:featured_at] == "1"
params[:taxon][:featured_at] = Time.now
else
params[:taxon][:featured_at] = ""
end
true
end
def amphibiaweb_description?
params[:description] != 'wikipedia' && try_amphibiaweb?
end
def try_amphibiaweb?
@taxon.species_or_lower? &&
@taxon.ancestor_ids.include?(Taxon::ICONIC_TAXA_BY_NAME['Amphibia'].id)
end
# Temp method for fetching amphibiaweb desc. Will probably implement this
# through TaxonLinks eventually
def get_amphibiaweb(taxon_names)
taxon_name = taxon_names.pop
return unless taxon_name
@genus_name, @species_name = taxon_name.name.split
url = "http://amphibiaweb.org/cgi/amphib_ws?where-genus=#{@genus_name}&where-species=#{@species_name}&src=eol"
Rails.logger.info "[INFO #{Time.now}] AmphibiaWeb request: #{url}"
xml = Nokogiri::XML(open(url))
if xml.blank? || xml.at(:error)
get_amphibiaweb(taxon_names)
else
xml
end
end
def ensure_flickr_write_permission
@provider_authorization = current_user.provider_authorizations.first(:conditions => {:provider_name => 'flickr'})
if @provider_authorization.blank? || @provider_authorization.scope != 'write'
session[:return_to] = request.get? ? request.fullpath : request.env['HTTP_REFERER']
redirect_to auth_url_for('flickr', :scope => 'write')
return false
end
end
def load_single_taxon_map_data(taxon)
@taxon_range = taxon.taxon_ranges.without_geom.first
if params[:place_id] && (@place = Place.find_by_id(params[:place_id]))
@place_geometry = PlaceGeometry.without_geom.first(:conditions => {:place_id => @place.id})
end
@bounds = if @place && (bbox = @place.bounding_box)
GeoRuby::SimpleFeatures::Envelope.from_points([
Point.from_coordinates([bbox[1], bbox[0]]),
Point.from_coordinates([bbox[3], bbox[2]])
])
elsif @taxon_range
taxon.taxon_ranges.calculate(:extent, :geom)
else
Observation.of(taxon).calculate(:extent, :geom)
end
if @bounds
@extent = [
{:lon => @bounds.lower_corner.x, :lat => @bounds.lower_corner.y},
{:lon => @bounds.upper_corner.x, :lat => @bounds.upper_corner.y}
]
end
find_options = {
:select => "listed_taxa.id, place_id, last_observation_id, places.place_type, occurrence_status_level, establishment_means",
:joins => [:place],
:conditions => [
"place_id IS NOT NULL AND places.place_type = ?",
Place::PLACE_TYPE_CODES['County']
]
}
@county_listings = taxon.listed_taxa.all(find_options).index_by{|lt| lt.place_id}
find_options[:conditions][1] = Place::PLACE_TYPE_CODES['State']
@state_listings = taxon.listed_taxa.all(find_options).index_by{|lt| lt.place_id}
find_options[:conditions][1] = Place::PLACE_TYPE_CODES['Country']
@country_listings = taxon.listed_taxa.all(find_options).index_by{|lt| lt.place_id}
end
end
|
class TeamController < ApplicationController
def info
@team = Maintainer.first :conditions => {
:login => '@' + params[:name].downcase,
:team => 'yes' }
@acls = Acl.all :conditions => {
:login => '@' + params[:name].downcase,
:branch => 'Sisyphus',
:vendor => 'ALT Linux' }
if @team != nil
@leader = Team.find_by_sql(['SELECT teams.login, maintainers.name
FROM teams, maintainers
WHERE maintainers.login = teams.login
AND teams.name = ?
AND teams.branch = ?
AND teams.vendor = ?
AND leader = "yes"
LIMIT 1', '@' + params[:name], 'Sisyphus', 'ALT Linux' ])
@members = Team.find_by_sql(['SELECT teams.login, maintainers.name
FROM teams, maintainers
WHERE maintainers.login = teams.login
AND teams.name = ?
AND teams.branch = ?
AND teams.vendor = ?', '@' + params[:name], 'Sisyphus', 'ALT Linux' ])
else
render :action => "nosuchteam"
end
end
end
fix team controller for postgres
class TeamController < ApplicationController
def info
@team = Maintainer.first :conditions => {
:login => '@' + params[:name].downcase,
:team => 'yes' }
@acls = Acl.all :conditions => {
:login => '@' + params[:name].downcase,
:branch => 'Sisyphus',
:vendor => 'ALT Linux' }
if @team != nil
@leader = Team.find_by_sql(['SELECT teams.login, maintainers.name
FROM teams, maintainers
WHERE maintainers.login = teams.login
AND teams.name = ?
AND teams.branch = ?
AND teams.vendor = ?
AND leader = \'yes\'
LIMIT 1', '@' + params[:name], 'Sisyphus', 'ALT Linux' ])
@members = Team.find_by_sql(['SELECT teams.login, maintainers.name
FROM teams, maintainers
WHERE maintainers.login = teams.login
AND teams.name = ?
AND teams.branch = ?
AND teams.vendor = ?', '@' + params[:name], 'Sisyphus', 'ALT Linux' ])
else
render :action => "nosuchteam"
end
end
end
|
class UrlsController < AssetsController
content_model Url
def new
@content = Url.new
render :template => 'assets/new'
end
def create
unless params["url"["url"] =~ /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix
flash[:error] = "Entered URL was invalid!"
redirect_to "/urls/new"
return
end
@content = Url.new(params["url"])
@content.asset = Asset.create(:user => current_user, :name => params["asset"]["name"])
if @content.save
flash[:notice] = "Created new asset!"
redirect_to url_for(@content) + "/edit"
else
render :action => 'new'
end
end
def show
redirect_to @content.url
end
end
fix syntax error
class UrlsController < AssetsController
content_model Url
def new
@content = Url.new
render :template => 'assets/new'
end
def create
unless params["url"] =~ /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix
flash[:error] = "Entered URL was invalid!"
redirect_to "/urls/new"
return
end
@content = Url.new(params["url"])
@content.asset = Asset.create(:user => current_user, :name => params["asset"]["name"])
if @content.save
flash[:notice] = "Created new asset!"
redirect_to url_for(@content) + "/edit"
else
render :action => 'new'
end
end
def show
redirect_to @content.url
end
end
|
class UserController < ApplicationController
# SAM WORKS FROM THIS LINE TO LINE 49
def index
@all_users = User.all
end
#KEVIN STARTS WORKING FROM HERE DOWN
end
finished login controller
class UserController < ApplicationController
# SAM WORKS FROM THIS LINE TO LINE 49
def index
@all_users = User.all
end
def new_login
@the_user = User.find_by(email: params[:user][:email])
if @the_user.try(:authenticate, params[:user][:password])
session[:user_id] = @the_user.id
redirect_to questions_path
else
flash.now[:danger] = "Invalid email/password combination"
redirect_to login_path
end
end
#KEVIN STARTS WORKING FROM HERE DOWN
end
|
class UserController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to deals_path
else
flash[:notice] = "There was a problem with your submission"
redirect_to new_user_path
end
end
def show
@user = User.find(params[:id])
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
@user.assign_attributes(user_params)
if @user.save
redirect_to user_path(@user.id)
else
render :edit
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
session[:user_id] = nil
redirect_to root_path
end
private
def user_params
params.fetch(:user, {}).permit(:email, :username, :password, :phone_number, :avatar)
end
end
signup modal
class UserController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
redirect_to deals_path
else
flash[:notice] = "There was a problem with your submission"
redirect_to new_user_path
end
end
def show
@user = User.find(params[:id])
@vendor = Vendor.new
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
@user.assign_attributes(user_params)
if @user.save
redirect_to user_path(@user.id)
else
render :edit
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
session[:user_id] = nil
redirect_to root_path
end
private
def user_params
params.fetch(:user, {}).permit(:email, :username, :password, :phone_number, :avatar)
end
end
|
# app/controllers/user_controller.rb:
# Show information about a user.
#
# Copyright (c) 2007 UK Citizens Online Democracy. All rights reserved.
# Email: francis@mysociety.org; WWW: http://www.mysociety.org/
#
# $Id: user_controller.rb,v 1.71 2009-09-17 07:51:47 francis Exp $
class UserController < ApplicationController
# Show page about a user
def show
if MySociety::Format.simplify_url_part(params[:url_name], 'user', 32) != params[:url_name]
redirect_to :url_name => MySociety::Format.simplify_url_part(params[:url_name], 'user', 32), :status => :moved_permanently
return
end
@display_user = User.find(:first, :conditions => [ "url_name = ? and email_confirmed = ?", params[:url_name], true ])
if not @display_user
raise "user not found, url_name=" + params[:url_name]
end
@same_name_users = User.find(:all, :conditions => [ "name ilike ? and email_confirmed = ? and id <> ?", @display_user.name, true, @display_user.id ], :order => "created_at")
@is_you = !@user.nil? && @user.id == @display_user.id
# Use search query for this so can collapse and paginate easily
# XXX really should just use SQL query here rather than Xapian.
begin
@xapian_requests = perform_search([InfoRequestEvent], 'requested_by:' + @display_user.url_name, 'newest', 'request_collapse')
@xapian_comments = perform_search([InfoRequestEvent], 'commented_by:' + @display_user.url_name, 'newest', nil)
if (@page > 1)
@page_desc = " (page " + @page.to_s + ")"
else
@page_desc = ""
end
rescue
@xapian_requests = nil
@xapian_comments = nil
end
# Track corresponding to this page
@track_thing = TrackThing.create_track_for_user(@display_user)
@feed_autodetect = [ { :url => do_track_url(@track_thing, 'feed'), :title => @track_thing.params[:title_in_rss] } ]
# All tracks for the user
if @is_you
@track_things = TrackThing.find(:all, :conditions => ["tracking_user_id = ? and track_medium = ?", @display_user.id, 'email_daily'], :order => 'created_at desc')
@track_things_grouped = @track_things.group_by(&:track_type)
end
# Requests you need to describe
if @is_you
@undescribed_requests = @display_user.get_undescribed_requests
end
end
# Login form
def signin
work_out_post_redirect
# make sure we have cookies
if session.instance_variable_get(:@dbman)
if not session.instance_variable_get(:@dbman).instance_variable_get(:@original)
# try and set them if we don't
if !params[:again]
redirect_to signin_url(:r => params[:r], :again => 1)
return
end
render :action => 'no_cookies'
return
end
end
# remove "cookie setting attempt has happened" parameter if there is one and cookies worked
if params[:again]
redirect_to signin_url(:r => params[:r], :again => nil)
return
end
if not params[:user_signin]
# First time page is shown
render :action => 'sign'
return
else
@user_signin = User.authenticate_from_form(params[:user_signin], @post_redirect.reason_params[:user_name] ? true : false)
if @user_signin.errors.size > 0
# Failed to authenticate
render :action => 'sign'
return
else
# Successful login
if @user_signin.email_confirmed
session[:user_id] = @user_signin.id
session[:user_circumstance] = nil
session[:remember_me] = params[:remember_me] ? true : false
do_post_redirect @post_redirect
else
send_confirmation_mail @user_signin
end
return
end
end
end
# Create new account form
def signup
work_out_post_redirect
# Make the user and try to save it
@user_signup = User.new(params[:user_signup])
if !@user_signup.valid?
# Show the form
render :action => 'sign'
else
user_alreadyexists = User.find_user_by_email(params[:user_signup][:email])
if user_alreadyexists
already_registered_mail user_alreadyexists
return
else
# New unconfirmed user
@user_signup.email_confirmed = false
@user_signup.save!
send_confirmation_mail @user_signup
return
end
end
end
# Followed link in user account confirmation email.
# If you change this, change ApplicationController.test_code_redirect_by_email_token also
def confirm
post_redirect = PostRedirect.find_by_email_token(params[:email_token])
if post_redirect.nil?
render :template => 'user/bad_token.rhtml'
return
end
@user = post_redirect.user
@user.email_confirmed = true
@user.save!
session[:user_id] = @user.id
session[:user_circumstance] = post_redirect.circumstance
do_post_redirect post_redirect
end
# Logout form
def _do_signout
session[:user_id] = nil
session[:user_circumstance] = nil
session[:remember_me] = false
end
def signout
self._do_signout
if params[:r]
redirect_to params[:r]
else
redirect_to :controller => "general", :action => "frontpage"
end
end
# Change password (XXX and perhaps later email) - requires email authentication
def signchangepassword
if @user and ((not session[:user_circumstance]) or (session[:user_circumstance] != "change_password"))
# Not logged in via email, so send confirmation
params[:submitted_signchangepassword_send_confirm] = true
params[:signchangepassword] = { :email => @user.email }
end
if params[:submitted_signchangepassword_send_confirm]
# They've entered the email, check it is OK and user exists
if not MySociety::Validate.is_valid_email(params[:signchangepassword][:email])
flash[:error] = "That doesn't look like a valid email address. Please check you have typed it correctly."
render :action => 'signchangepassword_send_confirm'
return
end
user_signchangepassword = User.find_user_by_email(params[:signchangepassword][:email])
if user_signchangepassword
# Send email with login link to go to signchangepassword page
url = signchangepassword_url
if params[:pretoken]
url += "?pretoken=" + params[:pretoken]
end
post_redirect = PostRedirect.new(:uri => url , :post_params => {},
:reason_params => {
:web => "",
:email => "Then you can change your password on WhatDoTheyKnow.com",
:email_subject => "Change your password on WhatDoTheyKnow.com"
},
:circumstance => "change_password" # special login that lets you change your password
)
post_redirect.user = user_signchangepassword
post_redirect.save!
url = confirm_url(:email_token => post_redirect.email_token)
UserMailer.deliver_confirm_login(user_signchangepassword, post_redirect.reason_params, url)
else
# User not found, but still show confirm page to not leak fact user exists
end
render :action => 'signchangepassword_confirm'
elsif not @user
# Not logged in, prompt for email
render :action => 'signchangepassword_send_confirm'
else
# Logged in via special email change password link, so can offer form to change password
raise "internal error" unless (session[:user_circumstance] == "change_password")
if params[:submitted_signchangepassword_do]
@user.password = params[:user][:password]
@user.password_confirmation = params[:user][:password_confirmation]
if not @user.valid?
render :action => 'signchangepassword'
else
@user.save!
flash[:notice] = "Your password has been changed."
if params[:pretoken] and not params[:pretoken].empty?
post_redirect = PostRedirect.find_by_token(params[:pretoken])
do_post_redirect post_redirect
else
redirect_to user_url(@user)
end
end
else
render :action => 'signchangepassword'
end
end
end
# Change your email
def signchangeemail
if not authenticated?(
:web => "To change your email address used on WhatDoTheyKnow.com",
:email => "Then you can change your email address used on WhatDoTheyKnow.com",
:email_subject => "Change your email address used on WhatDoTheyKnow.com"
)
# "authenticated?" has done the redirect to signin page for us
return
end
if !params[:submitted_signchangeemail_do]
render :action => 'signchangeemail'
return
end
@signchangeemail = ChangeEmailValidator.new(params[:signchangeemail])
@signchangeemail.logged_in_user = @user
if !@signchangeemail.valid?
render :action => 'signchangeemail'
return
end
# if new email already in use, send email there saying what happened
user_alreadyexists = User.find_user_by_email(@signchangeemail.new_email)
if user_alreadyexists
UserMailer.deliver_changeemail_already_used(@user.email, @signchangeemail.new_email)
# it is important this screen looks the same as the one below, so
# you can't change to someone's email in order to tell if they are
# registered with that email on the site
render :action => 'signchangeemail_confirm'
return
end
# if not already, send a confirmation link to the new email address which logs
# them into the old email's user account, but with special user_circumstance
if (not session[:user_circumstance]) or (session[:user_circumstance] != "change_email")
post_redirect = PostRedirect.new(:uri => signchangeemail_url(), :post_params => params,
:circumstance => "change_email" # special login that lets you change your email
)
post_redirect.user = @user
post_redirect.save!
url = confirm_url(:email_token => post_redirect.email_token)
UserMailer.deliver_changeemail_confirm(@user, @signchangeemail.new_email, url)
# it is important this screen looks the same as the one above, so
# you can't change to someone's email in order to tell if they are
# registered with that email on the site
render :action => 'signchangeemail_confirm'
return
end
# circumstance is 'change_email', so can actually change the email
@user.email = @signchangeemail.new_email
@user.save!
flash[:notice] = "You have now changed your email address used on WhatDoTheyKnow.com"
redirect_to user_url(@user)
end
# Send a message to another user
def contact
@recipient_user = User.find(params[:id])
# Banned from messaging users?
if !authenticated_user.nil? && !authenticated_user.can_contact_other_users?
@details = authenticated_user.can_fail_html
render :template => 'user/banned'
return
end
# You *must* be logged into send a message to another user. (This is
# partly to avoid spam, and partly to have some equanimity of openess
# between the two users)
if not authenticated?(
:web => "To send a message to " + CGI.escapeHTML(@recipient_user.name),
:email => "Then you can send a message to " + @recipient_user.name + ".",
:email_subject => "Send a message to " + @recipient_user.name
)
# "authenticated?" has done the redirect to signin page for us
return
end
if params[:submitted_contact_form]
params[:contact][:name] = @user.name
params[:contact][:email] = @user.email
@contact = ContactValidator.new(params[:contact])
if @contact.valid?
ContactMailer.deliver_user_message(
@user,
@recipient_user,
main_url(user_url(@user)),
params[:contact][:subject],
params[:contact][:message]
)
flash[:notice] = "Your message to " + CGI.escapeHTML(@recipient_user.name) + " has been sent!"
redirect_to user_url(@recipient_user)
return
end
else
@contact = ContactValidator.new(
{ :message => "" + @recipient_user.name + ",\n\n\n\nYours,\n\n" + @user.name }
)
end
end
# River of News: What's happening with your tracked things
def river
@results = @user.nil? ? [] : @user.track_things.collect { |thing|
perform_search([InfoRequestEvent], thing.track_query, thing.params[:feed_sortby], nil).results
}.flatten.sort { |a,b| b[:model].created_at <=> a[:model].created_at }.first(20)
end
def set_profile_photo
# check they are logged in (the upload photo option is anyway only available when logged in)
if authenticated_user.nil?
flash[:error] = "You need to be logged in to change your profile photo."
redirect_to frontpage_url
return
end
if !params[:submitted_draft_profile_photo].nil?
# check for uploaded image
file_name = nil
file_content = nil
if !params[:file].nil?
file_name = params[:file].original_filename
file_content = params[:file].read
end
if file_name.nil?
flash[:error] = "Please choose a file containing your photo"
render :template => 'user/set_draft_profile_photo.rhtml'
return
end
# validate it
@draft_profile_photo = ProfilePhoto.new(:data => file_content, :draft => true)
if !@draft_profile_photo.valid?
# error page (uses @profile_photo's error fields in view to show errors)
render :template => 'user/set_draft_profile_photo.rhtml'
return
end
@draft_profile_photo.save
if params[:automatically_crop]
# no javascript, crop automatically
@profile_photo = ProfilePhoto.new(:data => @draft_profile_photo.data, :draft => false)
@user.set_profile_photo(@profile_photo)
@draft_profile_photo.destroy
flash[:notice] = "Thank you for updating your profile photo"
redirect_to user_url(@user)
return
end
render :template => 'user/set_crop_profile_photo.rhtml'
return
elsif !params[:submitted_crop_profile_photo].nil?
# crop the draft photo according to jquery parameters and set it as the users photo
draft_profile_photo = ProfilePhoto.find(params[:draft_profile_photo_id])
@profile_photo = ProfilePhoto.new(:data => draft_profile_photo.data, :draft => false,
:x => params[:x], :y => params[:y], :w => params[:w], :h => params[:h])
@user.set_profile_photo(@profile_photo)
draft_profile_photo.destroy
flash[:notice] = "Thank you for updating your profile photo"
redirect_to user_url(@user)
else
render :template => 'user/set_draft_profile_photo.rhtml'
end
end
def clear_profile_photo
# check they are logged in (the upload photo option is anyway only available when logged in)
if authenticated_user.nil?
flash[:error] = "You need to be logged in to clear your profile photo."
redirect_to frontpage_url
return
end
if @user.profile_photo
@user.profile_photo.destroy
end
flash[:notice] = "You've now cleared your profile photo"
redirect_to user_url(@user)
end
# before they've cropped it
def get_draft_profile_photo
profile_photo = ProfilePhoto.find(params[:id])
response.content_type = "image/png"
render_for_text(profile_photo.data)
end
# actual profile photo of a user
def get_profile_photo
@display_user = User.find(:first, :conditions => [ "url_name = ? and email_confirmed = ?", params[:url_name], true ])
if !@display_user
raise "user not found, url_name=" + params[:url_name]
end
if !@display_user.profile_photo
raise "user has no profile photo, url_name=" + params[:url_name]
end
response.content_type = "image/png"
render_for_text(@display_user.profile_photo.data)
end
# Change about me text on your profile page
def set_profile_about_me
if authenticated_user.nil?
flash[:error] = "You need to be logged in to change the text about you on your profile."
redirect_to frontpage_url
return
end
if !params[:submitted_about_me]
params[:about_me] = {}
params[:about_me][:about_me] = @user.about_me
@about_me = AboutMeValidator.new(params[:about_me])
render :action => 'set_profile_about_me'
return
end
@about_me = AboutMeValidator.new(params[:about_me])
if !@about_me.valid?
render :action => 'set_profile_about_me'
return
end
@user.about_me = @about_me.about_me
@user.save!
flash[:notice] = "You have now changed the text about you on your profile."
redirect_to user_url(@user)
end
private
# Decide where we are going to redirect back to after signin/signup, and record that
def work_out_post_redirect
# Redirect to front page later if nothing else specified
if not params[:r] and not params[:token]
params[:r] = "/"
end
# The explicit "signin" link uses this to specify where to go back to
if params[:r]
@post_redirect = PostRedirect.new(:uri => params[:r], :post_params => {},
:reason_params => {
:web => "",
:email => "Then you can sign in to WhatDoTheyKnow.com",
:email_subject => "Confirm your account on WhatDoTheyKnow.com"
})
@post_redirect.save!
params[:token] = @post_redirect.token
elsif params[:token]
# Otherwise we have a token (which represents a saved POST request)
@post_redirect = PostRedirect.find_by_token(params[:token])
end
end
# Ask for email confirmation
def send_confirmation_mail(user)
post_redirect = PostRedirect.find_by_token(params[:token])
post_redirect.user = user
post_redirect.save!
url = confirm_url(:email_token => post_redirect.email_token)
UserMailer.deliver_confirm_login(user, post_redirect.reason_params, url)
render :action => 'confirm'
end
# If they register again
def already_registered_mail(user)
post_redirect = PostRedirect.find_by_token(params[:token])
post_redirect.user = user
post_redirect.save!
url = confirm_url(:email_token => post_redirect.email_token)
UserMailer.deliver_already_registered(user, post_redirect.reason_params, url)
render :action => 'confirm' # must be same as for send_confirmation_mail above to avoid leak of presence of email in db
end
end
Clear profile photo only in POST
# app/controllers/user_controller.rb:
# Show information about a user.
#
# Copyright (c) 2007 UK Citizens Online Democracy. All rights reserved.
# Email: francis@mysociety.org; WWW: http://www.mysociety.org/
#
# $Id: user_controller.rb,v 1.71 2009-09-17 07:51:47 francis Exp $
class UserController < ApplicationController
# Show page about a user
def show
if MySociety::Format.simplify_url_part(params[:url_name], 'user', 32) != params[:url_name]
redirect_to :url_name => MySociety::Format.simplify_url_part(params[:url_name], 'user', 32), :status => :moved_permanently
return
end
@display_user = User.find(:first, :conditions => [ "url_name = ? and email_confirmed = ?", params[:url_name], true ])
if not @display_user
raise "user not found, url_name=" + params[:url_name]
end
@same_name_users = User.find(:all, :conditions => [ "name ilike ? and email_confirmed = ? and id <> ?", @display_user.name, true, @display_user.id ], :order => "created_at")
@is_you = !@user.nil? && @user.id == @display_user.id
# Use search query for this so can collapse and paginate easily
# XXX really should just use SQL query here rather than Xapian.
begin
@xapian_requests = perform_search([InfoRequestEvent], 'requested_by:' + @display_user.url_name, 'newest', 'request_collapse')
@xapian_comments = perform_search([InfoRequestEvent], 'commented_by:' + @display_user.url_name, 'newest', nil)
if (@page > 1)
@page_desc = " (page " + @page.to_s + ")"
else
@page_desc = ""
end
rescue
@xapian_requests = nil
@xapian_comments = nil
end
# Track corresponding to this page
@track_thing = TrackThing.create_track_for_user(@display_user)
@feed_autodetect = [ { :url => do_track_url(@track_thing, 'feed'), :title => @track_thing.params[:title_in_rss] } ]
# All tracks for the user
if @is_you
@track_things = TrackThing.find(:all, :conditions => ["tracking_user_id = ? and track_medium = ?", @display_user.id, 'email_daily'], :order => 'created_at desc')
@track_things_grouped = @track_things.group_by(&:track_type)
end
# Requests you need to describe
if @is_you
@undescribed_requests = @display_user.get_undescribed_requests
end
end
# Login form
def signin
work_out_post_redirect
# make sure we have cookies
if session.instance_variable_get(:@dbman)
if not session.instance_variable_get(:@dbman).instance_variable_get(:@original)
# try and set them if we don't
if !params[:again]
redirect_to signin_url(:r => params[:r], :again => 1)
return
end
render :action => 'no_cookies'
return
end
end
# remove "cookie setting attempt has happened" parameter if there is one and cookies worked
if params[:again]
redirect_to signin_url(:r => params[:r], :again => nil)
return
end
if not params[:user_signin]
# First time page is shown
render :action => 'sign'
return
else
@user_signin = User.authenticate_from_form(params[:user_signin], @post_redirect.reason_params[:user_name] ? true : false)
if @user_signin.errors.size > 0
# Failed to authenticate
render :action => 'sign'
return
else
# Successful login
if @user_signin.email_confirmed
session[:user_id] = @user_signin.id
session[:user_circumstance] = nil
session[:remember_me] = params[:remember_me] ? true : false
do_post_redirect @post_redirect
else
send_confirmation_mail @user_signin
end
return
end
end
end
# Create new account form
def signup
work_out_post_redirect
# Make the user and try to save it
@user_signup = User.new(params[:user_signup])
if !@user_signup.valid?
# Show the form
render :action => 'sign'
else
user_alreadyexists = User.find_user_by_email(params[:user_signup][:email])
if user_alreadyexists
already_registered_mail user_alreadyexists
return
else
# New unconfirmed user
@user_signup.email_confirmed = false
@user_signup.save!
send_confirmation_mail @user_signup
return
end
end
end
# Followed link in user account confirmation email.
# If you change this, change ApplicationController.test_code_redirect_by_email_token also
def confirm
post_redirect = PostRedirect.find_by_email_token(params[:email_token])
if post_redirect.nil?
render :template => 'user/bad_token.rhtml'
return
end
@user = post_redirect.user
@user.email_confirmed = true
@user.save!
session[:user_id] = @user.id
session[:user_circumstance] = post_redirect.circumstance
do_post_redirect post_redirect
end
# Logout form
def _do_signout
session[:user_id] = nil
session[:user_circumstance] = nil
session[:remember_me] = false
end
def signout
self._do_signout
if params[:r]
redirect_to params[:r]
else
redirect_to :controller => "general", :action => "frontpage"
end
end
# Change password (XXX and perhaps later email) - requires email authentication
def signchangepassword
if @user and ((not session[:user_circumstance]) or (session[:user_circumstance] != "change_password"))
# Not logged in via email, so send confirmation
params[:submitted_signchangepassword_send_confirm] = true
params[:signchangepassword] = { :email => @user.email }
end
if params[:submitted_signchangepassword_send_confirm]
# They've entered the email, check it is OK and user exists
if not MySociety::Validate.is_valid_email(params[:signchangepassword][:email])
flash[:error] = "That doesn't look like a valid email address. Please check you have typed it correctly."
render :action => 'signchangepassword_send_confirm'
return
end
user_signchangepassword = User.find_user_by_email(params[:signchangepassword][:email])
if user_signchangepassword
# Send email with login link to go to signchangepassword page
url = signchangepassword_url
if params[:pretoken]
url += "?pretoken=" + params[:pretoken]
end
post_redirect = PostRedirect.new(:uri => url , :post_params => {},
:reason_params => {
:web => "",
:email => "Then you can change your password on WhatDoTheyKnow.com",
:email_subject => "Change your password on WhatDoTheyKnow.com"
},
:circumstance => "change_password" # special login that lets you change your password
)
post_redirect.user = user_signchangepassword
post_redirect.save!
url = confirm_url(:email_token => post_redirect.email_token)
UserMailer.deliver_confirm_login(user_signchangepassword, post_redirect.reason_params, url)
else
# User not found, but still show confirm page to not leak fact user exists
end
render :action => 'signchangepassword_confirm'
elsif not @user
# Not logged in, prompt for email
render :action => 'signchangepassword_send_confirm'
else
# Logged in via special email change password link, so can offer form to change password
raise "internal error" unless (session[:user_circumstance] == "change_password")
if params[:submitted_signchangepassword_do]
@user.password = params[:user][:password]
@user.password_confirmation = params[:user][:password_confirmation]
if not @user.valid?
render :action => 'signchangepassword'
else
@user.save!
flash[:notice] = "Your password has been changed."
if params[:pretoken] and not params[:pretoken].empty?
post_redirect = PostRedirect.find_by_token(params[:pretoken])
do_post_redirect post_redirect
else
redirect_to user_url(@user)
end
end
else
render :action => 'signchangepassword'
end
end
end
# Change your email
def signchangeemail
if not authenticated?(
:web => "To change your email address used on WhatDoTheyKnow.com",
:email => "Then you can change your email address used on WhatDoTheyKnow.com",
:email_subject => "Change your email address used on WhatDoTheyKnow.com"
)
# "authenticated?" has done the redirect to signin page for us
return
end
if !params[:submitted_signchangeemail_do]
render :action => 'signchangeemail'
return
end
@signchangeemail = ChangeEmailValidator.new(params[:signchangeemail])
@signchangeemail.logged_in_user = @user
if !@signchangeemail.valid?
render :action => 'signchangeemail'
return
end
# if new email already in use, send email there saying what happened
user_alreadyexists = User.find_user_by_email(@signchangeemail.new_email)
if user_alreadyexists
UserMailer.deliver_changeemail_already_used(@user.email, @signchangeemail.new_email)
# it is important this screen looks the same as the one below, so
# you can't change to someone's email in order to tell if they are
# registered with that email on the site
render :action => 'signchangeemail_confirm'
return
end
# if not already, send a confirmation link to the new email address which logs
# them into the old email's user account, but with special user_circumstance
if (not session[:user_circumstance]) or (session[:user_circumstance] != "change_email")
post_redirect = PostRedirect.new(:uri => signchangeemail_url(), :post_params => params,
:circumstance => "change_email" # special login that lets you change your email
)
post_redirect.user = @user
post_redirect.save!
url = confirm_url(:email_token => post_redirect.email_token)
UserMailer.deliver_changeemail_confirm(@user, @signchangeemail.new_email, url)
# it is important this screen looks the same as the one above, so
# you can't change to someone's email in order to tell if they are
# registered with that email on the site
render :action => 'signchangeemail_confirm'
return
end
# circumstance is 'change_email', so can actually change the email
@user.email = @signchangeemail.new_email
@user.save!
flash[:notice] = "You have now changed your email address used on WhatDoTheyKnow.com"
redirect_to user_url(@user)
end
# Send a message to another user
def contact
@recipient_user = User.find(params[:id])
# Banned from messaging users?
if !authenticated_user.nil? && !authenticated_user.can_contact_other_users?
@details = authenticated_user.can_fail_html
render :template => 'user/banned'
return
end
# You *must* be logged into send a message to another user. (This is
# partly to avoid spam, and partly to have some equanimity of openess
# between the two users)
if not authenticated?(
:web => "To send a message to " + CGI.escapeHTML(@recipient_user.name),
:email => "Then you can send a message to " + @recipient_user.name + ".",
:email_subject => "Send a message to " + @recipient_user.name
)
# "authenticated?" has done the redirect to signin page for us
return
end
if params[:submitted_contact_form]
params[:contact][:name] = @user.name
params[:contact][:email] = @user.email
@contact = ContactValidator.new(params[:contact])
if @contact.valid?
ContactMailer.deliver_user_message(
@user,
@recipient_user,
main_url(user_url(@user)),
params[:contact][:subject],
params[:contact][:message]
)
flash[:notice] = "Your message to " + CGI.escapeHTML(@recipient_user.name) + " has been sent!"
redirect_to user_url(@recipient_user)
return
end
else
@contact = ContactValidator.new(
{ :message => "" + @recipient_user.name + ",\n\n\n\nYours,\n\n" + @user.name }
)
end
end
# River of News: What's happening with your tracked things
def river
@results = @user.nil? ? [] : @user.track_things.collect { |thing|
perform_search([InfoRequestEvent], thing.track_query, thing.params[:feed_sortby], nil).results
}.flatten.sort { |a,b| b[:model].created_at <=> a[:model].created_at }.first(20)
end
def set_profile_photo
# check they are logged in (the upload photo option is anyway only available when logged in)
if authenticated_user.nil?
flash[:error] = "You need to be logged in to change your profile photo."
redirect_to frontpage_url
return
end
if !params[:submitted_draft_profile_photo].nil?
# check for uploaded image
file_name = nil
file_content = nil
if !params[:file].nil?
file_name = params[:file].original_filename
file_content = params[:file].read
end
if file_name.nil?
flash[:error] = "Please choose a file containing your photo"
render :template => 'user/set_draft_profile_photo.rhtml'
return
end
# validate it
@draft_profile_photo = ProfilePhoto.new(:data => file_content, :draft => true)
if !@draft_profile_photo.valid?
# error page (uses @profile_photo's error fields in view to show errors)
render :template => 'user/set_draft_profile_photo.rhtml'
return
end
@draft_profile_photo.save
if params[:automatically_crop]
# no javascript, crop automatically
@profile_photo = ProfilePhoto.new(:data => @draft_profile_photo.data, :draft => false)
@user.set_profile_photo(@profile_photo)
@draft_profile_photo.destroy
flash[:notice] = "Thank you for updating your profile photo"
redirect_to user_url(@user)
return
end
render :template => 'user/set_crop_profile_photo.rhtml'
return
elsif !params[:submitted_crop_profile_photo].nil?
# crop the draft photo according to jquery parameters and set it as the users photo
draft_profile_photo = ProfilePhoto.find(params[:draft_profile_photo_id])
@profile_photo = ProfilePhoto.new(:data => draft_profile_photo.data, :draft => false,
:x => params[:x], :y => params[:y], :w => params[:w], :h => params[:h])
@user.set_profile_photo(@profile_photo)
draft_profile_photo.destroy
flash[:notice] = "Thank you for updating your profile photo"
redirect_to user_url(@user)
else
render :template => 'user/set_draft_profile_photo.rhtml'
end
end
def clear_profile_photo
if !request.post?
raise "Can only clear profile photo from POST request"
end
# check they are logged in (the upload photo option is anyway only available when logged in)
if authenticated_user.nil?
flash[:error] = "You need to be logged in to clear your profile photo."
redirect_to frontpage_url
return
end
if @user.profile_photo
@user.profile_photo.destroy
end
flash[:notice] = "You've now cleared your profile photo"
redirect_to user_url(@user)
end
# before they've cropped it
def get_draft_profile_photo
profile_photo = ProfilePhoto.find(params[:id])
response.content_type = "image/png"
render_for_text(profile_photo.data)
end
# actual profile photo of a user
def get_profile_photo
@display_user = User.find(:first, :conditions => [ "url_name = ? and email_confirmed = ?", params[:url_name], true ])
if !@display_user
raise "user not found, url_name=" + params[:url_name]
end
if !@display_user.profile_photo
raise "user has no profile photo, url_name=" + params[:url_name]
end
response.content_type = "image/png"
render_for_text(@display_user.profile_photo.data)
end
# Change about me text on your profile page
def set_profile_about_me
if authenticated_user.nil?
flash[:error] = "You need to be logged in to change the text about you on your profile."
redirect_to frontpage_url
return
end
if !params[:submitted_about_me]
params[:about_me] = {}
params[:about_me][:about_me] = @user.about_me
@about_me = AboutMeValidator.new(params[:about_me])
render :action => 'set_profile_about_me'
return
end
@about_me = AboutMeValidator.new(params[:about_me])
if !@about_me.valid?
render :action => 'set_profile_about_me'
return
end
@user.about_me = @about_me.about_me
@user.save!
flash[:notice] = "You have now changed the text about you on your profile."
redirect_to user_url(@user)
end
private
# Decide where we are going to redirect back to after signin/signup, and record that
def work_out_post_redirect
# Redirect to front page later if nothing else specified
if not params[:r] and not params[:token]
params[:r] = "/"
end
# The explicit "signin" link uses this to specify where to go back to
if params[:r]
@post_redirect = PostRedirect.new(:uri => params[:r], :post_params => {},
:reason_params => {
:web => "",
:email => "Then you can sign in to WhatDoTheyKnow.com",
:email_subject => "Confirm your account on WhatDoTheyKnow.com"
})
@post_redirect.save!
params[:token] = @post_redirect.token
elsif params[:token]
# Otherwise we have a token (which represents a saved POST request)
@post_redirect = PostRedirect.find_by_token(params[:token])
end
end
# Ask for email confirmation
def send_confirmation_mail(user)
post_redirect = PostRedirect.find_by_token(params[:token])
post_redirect.user = user
post_redirect.save!
url = confirm_url(:email_token => post_redirect.email_token)
UserMailer.deliver_confirm_login(user, post_redirect.reason_params, url)
render :action => 'confirm'
end
# If they register again
def already_registered_mail(user)
post_redirect = PostRedirect.find_by_token(params[:token])
post_redirect.user = user
post_redirect.save!
url = confirm_url(:email_token => post_redirect.email_token)
UserMailer.deliver_already_registered(user, post_redirect.reason_params, url)
render :action => 'confirm' # must be same as for send_confirmation_mail above to avoid leak of presence of email in db
end
end
|
# frozen_string_literal: true
require "rails_helper"
module Renalware
describe UKRDC::CreateEncryptedPatientXMLFiles do
let(:patient) do
create(
:patient,
ukrdc_external_id: SecureRandom.uuid,
send_to_rpv: true,
sent_to_ukrdc_at: nil,
updated_at: 1.day.ago
)
end
describe "#call" do
around(:each) do |example|
# Create a sandboxed temp dir in the Rails tmp folder for us to use for
# creating UKRDC files. Normally this location would be persistent e.g. at
# /var/ukrdc
rails_tmp_folder = Rails.root.join("tmp").to_s
Dir.mktmpdir(nil, rails_tmp_folder) do |dir|
Renalware.configure{ |config| config.ukrdc_working_path = dir }
example.run
end
end
context "when then operation succeeds" do
it "updates sent_to_ukrdc_at for each sent patient" do
travel_to(Time.zone.now) do
patient
expect{
described_class.new.call
}.to change{ patient.reload.sent_to_ukrdc_at }.to(Time.zone.now)
end
end
end
context "when then operation fails becuase the files canot be encryted" do
before do
# Force an encryption error
Renalware.configure { |config| config.ukrdc_gpg_keyring = "bad" }
end
it "rolls back the transaction so sent_to_ukrdc_at is not updated" do
travel_to(Time.zone.now) do
patient
expect{
described_class.new.call
}.to raise_error(RuntimeError)
expect(patient.reload.sent_to_ukrdc_at).to be_nil # unchanged
end
end
end
end
end
end
Remove encryption tests for now
CircleCI error
RuntimeError:
Error encrypting UKRDC files: gpg: can't create `/home/circleci/.gnupg/random_seed': No such file or directory
# frozen_string_literal: true
require "rails_helper"
module Renalware
describe UKRDC::CreateEncryptedPatientXMLFiles do
let(:patient) do
create(
:patient,
ukrdc_external_id: SecureRandom.uuid,
send_to_rpv: true,
sent_to_ukrdc_at: nil,
updated_at: 1.day.ago
)
end
# TODO: Removing tests for now as getting errors encypting files on CircleCI and need to look
# into it when more time.
describe "#call" do
# This causes an error on CircleCI:
# RuntimeError:
# Error encrypting UKRDC files: gpg: can't create `/home/circleci/.gnupg/random_seed':
# No such file or directory
# around(:each) do |example|
# # Create a sandboxed temp dir in the Rails tmp folder for us to use for
# # creating UKRDC files. Normally this location would be persistent e.g. at
# # /var/ukrdc
# rails_tmp_folder = Rails.root.join("tmp").to_s
# Dir.mktmpdir(nil, rails_tmp_folder) do |dir|
# Renalware.configure{ |config| config.ukrdc_working_path = dir }
# example.run
# end
# end
# context "when then operation succeeds" do
# it "updates sent_to_ukrdc_at for each sent patient" do
# travel_to(Time.zone.now) do
# patient
# expect{
# described_class.new.call
# }.to change{ patient.reload.sent_to_ukrdc_at }.to(Time.zone.now)
# end
# end
# end
# context "when then operation fails becuase the files canot be encryted" do
# before do
# # Force an encryption error
# Renalware.configure { |config| config.ukrdc_gpg_keyring = "bad" }
# end
# it "rolls back the transaction so sent_to_ukrdc_at is not updated" do
# travel_to(Time.zone.now) do
# patient
# expect{
# described_class.new.call
# }.to raise_error(RuntimeError)
# expect(patient.reload.sent_to_ukrdc_at).to be_nil # unchanged
# end
# end
# end
end
end
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Course::Assessment::ProgrammingEvaluationService do
describe Course::Assessment::ProgrammingEvaluationService::Result do
self::TIME_LIMIT_EXCEEDED_EXIT_CODE = 137
let(:exit_code) { 0 }
let(:test_report) { '' }
subject do
Course::Assessment::ProgrammingEvaluationService::Result.new('', '', test_report, exit_code)
end
describe '#error' do
context 'when the test report is not nil' do
context 'when the exit code is 0' do
it { is_expected.not_to be_error }
end
context 'when the exit code is nonzero' do
let(:exit_code) { 2 }
it { is_expected.not_to be_error }
end
end
context 'when the test_report is nil' do
let(:test_report) { nil }
context 'when the exit code is 0' do
it { is_expected.not_to be_error }
end
context 'when the exit code is nonzero' do
let(:exit_code) { 2 }
it { is_expected.to be_error }
end
end
end
describe '#time_limit_exceeded?' do
context 'when the process exits normally' do
it { is_expected.not_to be_time_limit_exceeded }
end
context 'when the process exits with a SIGKILL' do
let(:exit_code) { self.class::TIME_LIMIT_EXCEEDED_EXIT_CODE }
it { is_expected.to be_time_limit_exceeded }
end
end
describe '#exception' do
context 'when the result is not errored' do
it 'returns nil' do
expect(subject).not_to be_error
expect(subject.exception).to be_nil
end
end
context 'when the time limit is exceeded' do
let(:exit_code) { self.class::TIME_LIMIT_EXCEEDED_EXIT_CODE }
let(:test_report) { nil }
it 'returns TimeLimitExceededError' do
expect(subject).to be_time_limit_exceeded
expect(subject.exception).to \
be_a(Course::Assessment::ProgrammingEvaluationService::TimeLimitExceededError)
end
end
context 'when there are all other errors' do
let(:exit_code) { 2 }
let(:test_report) { nil }
it 'returns Error' do
expect(subject).to be_error
expect(subject.exception).to be_a(Course::Assessment::ProgrammingEvaluationService::Error)
end
end
end
end
subject { Course::Assessment::ProgrammingEvaluationService }
let(:instance) { Instance.default }
with_tenant(:instance) do
let(:course) { create(:course) }
it 'returns the result of evaluating' do
result = subject.execute(course,
Coursemology::Polyglot::Language::Python::Python2Point7.instance, 64,
5.seconds, File.join(Rails.root, 'spec', 'fixtures', 'course',
'programming_question_template.zip'))
expect(result).to be_a(Course::Assessment::ProgrammingEvaluationService::Result)
end
context 'when the evaluation times out' do
it 'raises a Timeout::Error' do
expect do
# Pass in a non-zero timeout as Ruby's Timeout treats 0 as infinite.
subject.execute(course, Coursemology::Polyglot::Language::Python::Python2Point7.instance,
64, 5.seconds, File.join(Rails.root, 'spec', 'fixtures', 'course',
'programming_question_template.zip'),
0.1.seconds)
end.to raise_error(Timeout::Error)
end
end
end
end
Add specs for create_container in ProgrammingEvaluationService.
Adapted from corresponding specs in evaluator-slave.
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Course::Assessment::ProgrammingEvaluationService do
describe Course::Assessment::ProgrammingEvaluationService::Result do
self::TIME_LIMIT_EXCEEDED_EXIT_CODE = 137
let(:exit_code) { 0 }
let(:test_report) { '' }
subject do
Course::Assessment::ProgrammingEvaluationService::Result.new('', '', test_report, exit_code)
end
describe '#error' do
context 'when the test report is not nil' do
context 'when the exit code is 0' do
it { is_expected.not_to be_error }
end
context 'when the exit code is nonzero' do
let(:exit_code) { 2 }
it { is_expected.not_to be_error }
end
end
context 'when the test_report is nil' do
let(:test_report) { nil }
context 'when the exit code is 0' do
it { is_expected.not_to be_error }
end
context 'when the exit code is nonzero' do
let(:exit_code) { 2 }
it { is_expected.to be_error }
end
end
end
describe '#time_limit_exceeded?' do
context 'when the process exits normally' do
it { is_expected.not_to be_time_limit_exceeded }
end
context 'when the process exits with a SIGKILL' do
let(:exit_code) { self.class::TIME_LIMIT_EXCEEDED_EXIT_CODE }
it { is_expected.to be_time_limit_exceeded }
end
end
describe '#exception' do
context 'when the result is not errored' do
it 'returns nil' do
expect(subject).not_to be_error
expect(subject.exception).to be_nil
end
end
context 'when the time limit is exceeded' do
let(:exit_code) { self.class::TIME_LIMIT_EXCEEDED_EXIT_CODE }
let(:test_report) { nil }
it 'returns TimeLimitExceededError' do
expect(subject).to be_time_limit_exceeded
expect(subject.exception).to \
be_a(Course::Assessment::ProgrammingEvaluationService::TimeLimitExceededError)
end
end
context 'when there are all other errors' do
let(:exit_code) { 2 }
let(:test_report) { nil }
it 'returns Error' do
expect(subject).to be_error
expect(subject.exception).to be_a(Course::Assessment::ProgrammingEvaluationService::Error)
end
end
end
end
let(:instance) { Instance.default }
with_tenant(:instance) do
subject { Course::Assessment::ProgrammingEvaluationService }
let(:course) { create(:course) }
it 'returns the result of evaluating' do
result = subject.execute(course,
Coursemology::Polyglot::Language::Python::Python2Point7.instance, 64,
5.seconds, File.join(Rails.root, 'spec', 'fixtures', 'course',
'programming_question_template.zip'))
expect(result).to be_a(Course::Assessment::ProgrammingEvaluationService::Result)
end
context 'when the evaluation times out' do
it 'raises a Timeout::Error' do
expect do
# Pass in a non-zero timeout as Ruby's Timeout treats 0 as infinite.
subject.execute(course, Coursemology::Polyglot::Language::Python::Python2Point7.instance,
64, 5.seconds, File.join(Rails.root, 'spec', 'fixtures', 'course',
'programming_question_template.zip'),
0.1.seconds)
end.to raise_error(Timeout::Error)
end
end
describe '#create_container' do
let(:memory_limit) { nil }
let(:time_limit) { nil }
let(:service_instance) do
subject.new(course, Coursemology::Polyglot::Language::Python::Python2Point7.instance,
memory_limit, time_limit, Rails.root.join('spec', 'fixtures', 'course',
'programming_question_template.zip'),
nil)
end
let(:image) { 'python:2.7' }
let(:container) { service_instance.send(:create_container, image) }
it 'prefixes the image with coursemology/evaluator-image' do
# 30 seconds is the default time limit when unspecified.
expect(CoursemologyDockerContainer).to \
receive(:create).with("coursemology/evaluator-image-#{image}",
hash_including(argv: ['-c30']))
container
end
context 'when resource limits are specified' do
let(:memory_limit) { 16 }
let(:time_limit) { 5 }
it 'specifies them when creating the container' do
expect(CoursemologyDockerContainer).to \
receive(:create).with("coursemology/evaluator-image-#{image}",
hash_including(argv: ['-c5', '-m16384']))
container
end
end
end
end
end
|
require "adapters"
class PublishingAdapter
def save(manual, republish: false, include_sections: true)
update_type = (republish ? "republish" : nil)
organisation = organisation_for(manual)
save_manual_links(manual)
ManualPublishingAPIExporter.new(
organisation, manual, update_type: update_type
).call
if include_sections
manual.sections.each do |section|
next if !section.needs_exporting? && !republish
save_section(section, manual, update_type: update_type)
end
end
end
def save_section(section, manual, update_type: nil)
organisation = organisation_for(manual)
SectionPublishingAPILinksExporter.new(
organisation, manual, section
).call
SectionPublishingAPIExporter.new(
organisation, manual, section, update_type: update_type
).call
end
private
def organisation_for(manual)
Adapters.organisations.find(manual.organisation_slug)
end
def save_manual_links(manual)
organisation = organisation_for(manual)
Services.publishing_api.patch_links(
manual.id,
links: {
organisations: [organisation.content_id],
sections: manual.sections.map(&:uuid),
}
)
end
end
Extract PublishingAdapter#save_manual_content
To improve readability. As before there shouldn't be a performance hit
even though we're now looking up the organisation every time we export
the content for a manual as well as elsewhere, because the organisation
will be cached in `OrganisationsAdapter`.
I'm expecting this method to get bigger as I inline logic from
`ManualPublishingAPIExporter`.
Note that I'm planning to extract other methods along similar lines.
require "adapters"
class PublishingAdapter
def save(manual, republish: false, include_sections: true)
update_type = (republish ? "republish" : nil)
save_manual_links(manual)
save_manual_content(manual, update_type: update_type)
if include_sections
manual.sections.each do |section|
next if !section.needs_exporting? && !republish
save_section(section, manual, update_type: update_type)
end
end
end
def save_section(section, manual, update_type: nil)
organisation = organisation_for(manual)
SectionPublishingAPILinksExporter.new(
organisation, manual, section
).call
SectionPublishingAPIExporter.new(
organisation, manual, section, update_type: update_type
).call
end
private
def organisation_for(manual)
Adapters.organisations.find(manual.organisation_slug)
end
def save_manual_links(manual)
organisation = organisation_for(manual)
Services.publishing_api.patch_links(
manual.id,
links: {
organisations: [organisation.content_id],
sections: manual.sections.map(&:uuid),
}
)
end
def save_manual_content(manual, update_type: nil)
organisation = organisation_for(manual)
ManualPublishingAPIExporter.new(
organisation, manual, update_type: update_type
).call
end
end
|
Beginnings of grabber test code.
require File.dirname(__FILE__) + '/helper'
class GenericHttpGrabberTest < Test::Unit::TestCase
context "The GenericHttpGrabber" do
end
end
|
[bosh_cli] add maintenance command spec
require 'spec_helper'
describe Bosh::Cli::Command::Maintenance do
let(:command) { described_class.new }
let(:director) { double(Bosh::Cli::Director) }
before do
command.stub(:director).and_return(director)
command.options[:non_interactive] = true
command.options[:username] = 'admin'
command.options[:password] = 'admin'
command.options[:target] = 'http://example.org'
director.stub(list_stemcells: [])
end
context 'old releases format' do
let(:release) do
{
'name' => 'release-1',
'versions' => ['2.1-dev', '15', '2', '1'],
'in_use' => ['2.1-dev']
}
end
it 'should cleanup releases' do
director.stub(list_releases: [release])
director.should_receive(:delete_release).
with('release-1', force: false, version: '1', quiet: true).
and_return([:done, 1])
director.should_receive(:delete_release).
with('release-1', force: false, version: '2', quiet: true).
and_return([:done, 2])
command.cleanup
end
end
context 'new releases format' do
let(:release) do
{
'name' => 'release-1',
'release_versions' => [
{'version' => '2.1-dev', 'commit_hash' => 'unknown', 'uncommitted_changes' => false, 'currently_deployed' => true},
{'version' => '15', 'commit_hash' => '1a2b3c4d', 'uncommitted_changes' => true, 'currently_deployed' => false},
{'version' => '2', 'commit_hash' => '00000000', 'uncommitted_changes' => true, 'currently_deployed' => false},
{'version' => '1', 'commit_hash' => 'unknown', 'uncommitted_changes' => false, 'currently_deployed' => false}
]
}
end
it 'should cleanup releases' do
director.stub(list_releases: [release])
director.should_receive(:delete_release).
with('release-1', force: false, version: '1', quiet: true).
and_return([:done, 1])
director.should_receive(:delete_release).
with('release-1', force: false, version: '2', quiet: true).
and_return([:done, 2])
command.cleanup
end
end
end
|
#!/usr/bin/env ruby
# Run a distributed test and compare to dbtoaster results
require 'optparse'
require 'fileutils'
require 'pathname'
require 'yaml'
require 'csv'
require 'open3'
$tables = {'sentinel' => 'st',
'customer' => 'ci',
'lineitem' => 'li',
'orders' => 'or',
'part' => 'pt',
'partsupp' => 'ps',
'supplier' => 'su'
}
def create_files()
# Compile the k3 file
if $options[:compile]
puts "Compiling mosaic_tpch_polyfile.k3"
compile_path = File.join($k3_root_path, "tools", "scripts", "run", "compile.sh")
clean_path = File.join($k3_root_path, "tools", "scripts", "run", "clean.sh")
k3_path = File.join($k3_root_path, "examples", "loaders", "mosaic_tpch_polyfile.k3")
`#{clean_path}`
`#{compile_path} #{k3_path}`
end
out_path = $options[:output_path]
FileUtils.mkdir_p(out_path) unless Dir.exists?(out_path)
old_pwd = FileUtils.pwd
# Change dir for prog output to go to the right place
FileUtils.cd(out_path)
num_batches = {}
main_yaml = {
'me' => ["127.0.0.1", 30000],
'batch_sz' => $options[:batch_size],
}
prog_path = File.join($k3_root_path, "__build", "A")
# Loop over all tables
$tables.each_key do |table|
print "Handling table #{table}..."
files =
if table == "sentinel" then []
else
p = [$options[:input_path]] +
($options[:recurse] ? ['**'] : []) +
["#{table}*"]
paths = []
Dir.glob(File.join(*p)) do |f|
if File.directory?(f) then next end
basename = Pathname.new(f).basename.to_s
# check against regex
if basename =~ /#{$options[:regex]}/
paths << f
end
end
paths
end
yaml = main_yaml
yaml['role'] = [{'i' => "go_#{table}"}]
yaml['files'] = files.map { |s| {'path' => s} }
yaml = yaml.to_yaml
File.open('temp.yaml', 'w') { |f| f.puts(yaml) }
`#{prog_path} -p temp.yaml | tee temp.out`
out_file = table + ".out"
FileUtils.mv('p' + out_file, out_file)
# get number of batches
if table == 'sentinel'
num_batches[table] = 1
puts "1 batch"
else
s = File.open("temp.out", 'r').read()
num = s[/^Saved: (\d+) batches.$/m, 1].to_i
puts "#{num} batch#{num == 1 ? '' : 'es'}"
if num && num != '0' then
num_batches[table] = num
end
end
end
# create order file
yaml = main_yaml
yaml['role'] = [{'i' => 'go_exact_mux'}]
$tables.each do |table, short|
yaml["num" + short] = num_batches[table]
end
yaml = yaml.to_yaml
File.open('temp_mux.yaml', 'w') { |f| f.puts(yaml) }
`#{prog_path} -p temp_mux.yaml | tee temp.out`
# test
if $options[:test]
table_list = %w{sentinel customer lineitem orders part partsupp supplier}
FileUtils.cp('out_order.csv', 'in_order.csv')
yaml = main_yaml
yaml['seqfiles'] = table_list.map {|t| {'seq' => [{'path' => "#{t}.out"}]} }
yaml['role'] = [{'i' => 'loadseq'}]
yaml = yaml.to_yaml
File.open('temp_test.yaml', 'w') { |f| f.puts(yaml) }
`#{prog_path} -p temp_test.yaml | tee temp.out`
end
# restore pwd
FileUtils.cd(old_pwd)
end
$options = {
:batch_size => 10000,
:input_path => 'tools/ktrace/data/tpch',
:output_path => './',
:compile => false,
:recurse => false, # search recursively for input files
:regex => '.+', # limit input files to specific regex patterns
:test => false
}
$script_path = File.expand_path(File.dirname(__FILE__))
$k3_root_path = File.expand_path(File.join($script_path, "..", "..", ".."))
def main()
usage = "Usage: #{$PROGRAM_NAME} options input_path"
parser = OptionParser.new do |opts|
opts.banner = usage
opts.on("-b", "--batchsize NUM", "Size of batch") {|s| $options[:batch_size] = s.to_i}
opts.on("-o", "--output PATH", "Output path") {|s| $options[:output_path] = s}
opts.on("--compile", "Don't compile K3") { $options[:compile] = true }
opts.on("-r", "--recurse", "Input path: recursively search for files") { $options[:recurse] = true }
opts.on("-x", "--regex STR", "Regex string") { |s| $options[:regex] = s }
opts.on("-t", "--test", "Test data loading") { $options[:test] = true }
end
parser.parse!
unless ARGV.size == 1
puts "Must have a source path"
exit(1)
end
$options[:input_path] = File.expand_path(ARGV[0])
create_files()
end
main
mosaic/create_fpb: add all functionality
#!/usr/bin/env ruby
# Create the fpb files from the default dbgen files
#
#
# Stages:
# Note: We assume the dbgen files are already created and split into table.dddd (d=digit)
# (running dbgen to produce the files takes too long)
# Since we support at most 128 switches, the files must be divided into 128 chunks each.
# - Split the tbl files from dbgen into 1024 shards each
# - Compile the k3 program necessary to run.
# - For each table, for each shard, run the k3 program, producing an output file
# - Store the number of batches in each (table,shard)
# - Create mux files for the powerset of the tables, for each split of switches up to 128.
require 'optparse'
require 'fileutils'
require 'pathname'
require 'yaml'
require 'csv'
require 'open3'
$script_path = File.expand_path(File.dirname(__FILE__))
$k3_root_path = File.expand_path(File.join($script_path, "..", "..", ".."))
$tables = {
:sentinel => 'st',
:customer => 'ci',
:lineitem => 'li',
:orders => 'or',
:part => 'pt',
:partsupp => 'ps',
:supplier => 'su'
}
# numbers for table
$tags = {
:customer => 1,
:lineitem => 2,
:orders => 3,
:part => 4,
:partsupp => 5,
:supplier => 6
}
# split the original tpch files into 1024 files
def split_files(path)
pwd = FileUtils.pwd
puts "Splitting files in #{path}"
$tables.each_key do |table|
next if table == :sentinel
puts "Handling #{table}..."
table_path = File.join(path, table)
FileUtils.rm_r(table_path) if File.exist?(table_path)
FileUtils.mkdir_p(table_path) unless File.exist?(table_path)
FileUtils.chdir(table_path)
`split --number=l/128 --numeric-suffixes --suffix-length=4 ../#{table}.tbl #{table}`
end
FileUtils.chdir(pwd)
end
# First stage after generating tbl files using dbgen:
# split all the files in a path's subdirectories
def split_all_files(path)
Dir.glob(File.join(path, '*')).sort.each do |file|
split_files(file) if File.directory?(file)
end
end
# Step 2, compiling the k3 file (if requested)
def compile_k3()
puts "Compiling mosaic_tpch_polyfile.k3"
compile_path = File.join($k3_root_path, "tools", "scripts", "run", "compile.sh")
clean_path = File.join($k3_root_path, "tools", "scripts", "run", "clean.sh")
k3_path = File.join($k3_root_path, "examples", "loaders", "mosaic_tpch_polyfile.k3")
`#{clean_path}`
`#{compile_path} #{k3_path}`
end
def make_yaml()
{ 'me' => ["127.0.0.1", 30000] }
end
# create the TPCH FPB files, returning a map of table -> 4-digit num -> batches
def create_data_files(in_path, out_path)
num_batches = {}
$tables.each_key { |t| num_batches[t] = {} }
prog_path = File.join($k3_root_path, "__build", "A")
# Loop over all tables
$tables.each_key do |table|
puts "Converting table #{table}..."
out_table_path = File.join(out_path, table.to_s)
FileUtils.mkdir_p(out_table_path) unless Dir.exists?(out_table_path)
# create yaml
yaml = make_yaml
yaml['batch_sz'] = $options[:batch_size]
yaml['role'] = [{'i' => "go_#{table}"}]
yaml['files'] = []
# We operate per file, getting its batch numbers
if table == :sentinel
File.open('temp.yaml', 'w') { |f| f.puts(yaml.to_yaml) }
`#{prog_path} -p temp.yaml | tee temp.out`
FileUtils.mv('psentinel.out', File.join(out_table_path, 'sentinel.out'))
puts "1 batch"
else
# loop over every data file
p = [in_path] + ($options[:recurse] ? ['**'] : []) + ["#{table}*"]
Dir.glob(File.join(*p)).sort.each do |file|
# check that it's a file
next if File.directory?(file)
basename = File.basename(file)
# check against regex
next unless basename =~ /#{$options[:regex]}/
file_num = basename[/\D*(\d+)/, 1]
yaml['files'] = [file].map { |s| {'path' => s} }
File.open('temp.yaml', 'w') { |f| f.puts(yaml.to_yaml) }
`#{prog_path} -p temp.yaml | tee temp.out`
FileUtils.mv("p#{table}.out", File.join(out_table_path, "#{table}#{file_num}"))
# get & save number of batches
str = File.open("temp.out", 'r').read()
v = str[/^Saved: (\d+) batches.$/m, 1].to_i
puts "File #{basename}: #{v} batch#{v == 1 ? '' : 'es'}"
num_batches[table][file_num.to_i] = v
end
end
end
num_batches
end
def mux_path(out_path, part, num_switches, suffix)
File.join(out_path, num_switches.to_s, "mux_#{part}_#{num_switches}_#{suffix}.csv")
end
def mux_full_path(out_path, part, num_switches)
mux_path(out_path, part, num_switches, 'full')
end
# accepts the map from create_data_files to create the order files
# @num_switches: how many partitions we'll actually make use of
def create_order_files(out_path, batch_map, num_switches)
# partition map for this number of switches
partitions = {}
# create subdir
dir = File.join(out_path, num_switches.to_s)
FileUtils.mkdir_p(dir) unless File.exist? dir
(0...num_switches).each {|i| partitions[i] = {}}
batch_map.each do |table, map|
map.each do |num, count|
i = num % num_switches
partitions[i][table] =
partitions[i].has_key?(table) ? partitions[i][table] + count : 0
end
end
# linearize and randomize each partition
partitions.each do |num_part, tables|
list = []
tables.each do |table, count|
list += [$tags[table]] * count
end
mux_path = mux_full_path(out_path, num_part, num_switches)
File.open(mux_path, 'w') do |f|
f.puts(list.shuffle)
f.puts('0')
end
end
# Now do the powerset for each partition: filter out the tables we don't need
# Go over each possible length
(1..$tags.length - 1).each do |t|
# create all possible combinations of that length
$tags.keys.combination(t).each do |combo|
included_tags = combo.map {|k| $tags[k]}
id = combo.join('_')
partitions.each_key do |i|
puts "----- Generating Partition #{i} with #{t} tags: #{combo.to_s} ------"
# filter out the lines that don't match our included tags
File.open(mux_path(out_path, i, num_switches, id), 'w') do |outf|
File.open(mux_full_path(out_path, i, num_switches), 'r') do |inf|
inf.each_line do |line|
outf.puts line if included_tags.include? (line.to_i)
end
end
outf.puts '0' # sentinel
end
end
end
end
end
# create files for a single scale factor
def create_sf_files(in_path, out_path)
FileUtils.mkdir_p(out_path) unless File.exists? out_path
batch_path = File.join(out_path, 'batch.yaml')
unless $options[:mux_only]
# create the fpbs
batch_map = create_data_files(in_path, out_path)
# save the batch map
File.open(batch_path, 'w') {|f| f.write(batch_map.to_yaml)}
end
# load the batch map from the file
if !File.exist?(batch_path)
puts "#{batch_path} doesn't exist"
exit(1)
end
batch_map = YAML.load_file(batch_path)
# create the mux files
mux_path = File.join(out_path, 'mux')
FileUtils.mkdir_p(mux_path) unless File.exists? mux_path
[1, 2, 4, 8, 16, 32, 64].each do |num_switches|
create_order_files(mux_path, batch_map, num_switches)
end
end
# create for all scale factors
def create_all_sf_files(in_path, out_path)
Dir.glob(File.join(in_path, "*")).sort.each do |f|
next unless File.directory? f
basename = File.basename(f)
create_sf_files(File.join(in_path, basename), File.join(out_path, basename))
end
end
def run_load_test
# test
if $options[:test]
table_list = %w{sentinel customer lineitem orders part partsupp supplier}
FileUtils.cp('out_order.csv', 'in_order.csv')
yaml = make_yaml
yaml['batch_sz'] = $options[:batch_size]
yaml['seqfiles'] = table_list.map {|t| {'seq' => [{'path' => "#{t}.out"}]} }
yaml['role'] = [{'i' => 'loadseq'}]
yaml = yaml.to_yaml
File.open('temp_test.yaml', 'w') { |f| f.puts(yaml) }
prog_path = File.join($k3_root_path, "__build", "A")
`#{prog_path} -p temp_test.yaml | tee temp_test.out`
end
end
$options = {
:batch_size => 10000,
:input_path => 'tools/ktrace/data/tpch',
:output_path => './',
:compile => false,
:mux_only => false,
:recurse => true, # search recursively for input files
:regex => '^\D+\d\d\d\d$', # limit input files to specific regex patterns
:test => false,
:split_tpch => false,
:action => :none
}
def main()
usage = "Usage: #{$PROGRAM_NAME} options input_path"
parser = OptionParser.new do |opts|
opts.banner = usage
opts.on("-b", "--batchsize NUM", "Size of batch") {|s| $options[:batch_size] = s.to_i}
opts.on("-o", "--output PATH", "Output path") {|s| $options[:output_path] = s}
opts.on("--split-tpch", "Split TPCH .tbl files") { $options[:split_tpch] = true }
opts.on("--compile", "Compile K3") { $options[:compile] = true }
opts.on("--mux-only", "Mux file only") { $options[:mux_only] = true }
opts.on("-1", '--one', 'Single set of SF files') { $options[:action] = :one }
opts.on("-a", '--all', 'Many SF files') { $options[:action] = :all }
# for handline test ktrace data
opts.on("-r", "--recurse", "Input path: recursively search for files") { $options[:recurse] = true }
opts.on("-x", "--regex STR", "Regex test files") { |s| $options[:regex] = s }
opts.on("-t", "--test", "Test data loading") { $options[:test] = true }
end
parser.parse!
unless ARGV.size == 1
puts "Must have a source path"
exit(1)
end
$options[:input_path] = File.expand_path(ARGV[0])
compile_k3 if $options[:compile]
split_all_files($options[:input_path]) if $options[:split_tpch]
case $options[:action]
when :all
create_all_sf_files($options[:input_path], $options[:output_path])
when :one
create_sf_files($options[:input_path], $options[:output_path])
end
run_load_test if $options[:test]
end
main if __FILE__ == $0
|
require_relative '../common'
require 'logger'
require 'net/ssh/transport/algorithms'
module Transport
class TestAlgorithms < NetSSHTest
include Net::SSH::Transport::Constants
def test_allowed_packets
(0..255).each do |type|
packet = stub("packet", type: type)
case type
when 1..4, 6..19, 21..49 then assert(Net::SSH::Transport::Algorithms.allowed_packet?(packet), "#{type} should be allowed during key exchange")
else assert(!Net::SSH::Transport::Algorithms.allowed_packet?(packet), "#{type} should not be allowed during key exchange")
end
end
end
def test_constructor_should_build_default_list_of_preferred_algorithms
assert_equal ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa ssh-dss], algorithms[:host_key]
assert_equal ec_kex + %w[diffie-hellman-group-exchange-sha256 diffie-hellman-group-exchange-sha1 diffie-hellman-group14-sha1 diffie-hellman-group1-sha1], algorithms[:kex]
assert_equal %w[aes256-ctr aes192-ctr aes128-ctr aes256-cbc aes192-cbc aes128-cbc rijndael-cbc@lysator.liu.se blowfish-ctr blowfish-cbc cast128-ctr cast128-cbc 3des-ctr 3des-cbc idea-cbc none], algorithms[:encryption]
if defined?(OpenSSL::Digest::SHA256)
assert_equal %w[hmac-sha2-512 hmac-sha2-256 hmac-sha2-512-96 hmac-sha2-256-96 hmac-sha1 hmac-sha1-96 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 hmac-md5-96 none], algorithms[:hmac]
else
assert_equal %w[hmac-sha1 hmac-sha1-96 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 hmac-md5-96 none], algorithms[:hmac]
end
assert_equal %w[none zlib@openssh.com zlib], algorithms[:compression]
assert_equal %w[], algorithms[:language]
end
def test_constructor_should_set_client_and_server_prefs_identically
%w[encryption hmac compression language].each do |key|
assert_equal algorithms[key.to_sym], algorithms[:"#{key}_client"], key
assert_equal algorithms[key.to_sym], algorithms[:"#{key}_server"], key
end
end
def test_constructor_with_preferred_host_key_type_should_put_preferred_host_key_type_first
assert_equal %w[ssh-dss] + ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa], algorithms(host_key: "ssh-dss", append_all_supported_algorithms: true)[:host_key]
end
def test_constructor_with_known_hosts_reporting_known_host_key_should_use_that_host_key_type
Net::SSH::KnownHosts.expects(:search_for).with("net.ssh.test,127.0.0.1", {}).returns([stub("key", ssh_type: "ssh-dss")])
assert_equal %w[ssh-dss] + ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa], algorithms[:host_key]
end
def ed_host_keys
if Net::SSH::Authentication::ED25519Loader::LOADED
%w[ssh-ed25519-cert-v01@openssh.com ssh-ed25519]
else
[]
end
end
def ec_host_keys
if defined?(OpenSSL::PKey::EC)
%w[ecdsa-sha2-nistp521-cert-v01@openssh.com
ecdsa-sha2-nistp384-cert-v01@openssh.com
ecdsa-sha2-nistp256-cert-v01@openssh.com
ecdsa-sha2-nistp521
ecdsa-sha2-nistp384
ecdsa-sha2-nistp256]
else
[]
end
end
def ed_ec_host_keys
ed_host_keys + ec_host_keys
end
def test_constructor_with_unrecognized_host_key_type_should_return_whats_supported
assert_equal ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa ssh-dss], algorithms(host_key: "bogus ssh-rsa",append_all_supported_algorithms: true)[:host_key]
end
def ec_kex
if defined?(OpenSSL::PKey::EC)
%w[ecdh-sha2-nistp521 ecdh-sha2-nistp384 ecdh-sha2-nistp256]
else
[]
end
end
def test_constructor_with_preferred_kex_should_put_preferred_kex_first
assert_equal %w[diffie-hellman-group1-sha1] + ec_kex + %w[diffie-hellman-group-exchange-sha256 diffie-hellman-group-exchange-sha1 diffie-hellman-group14-sha1], algorithms(kex: "diffie-hellman-group1-sha1", append_all_supported_algorithms: true)[:kex]
end
def test_constructor_with_unrecognized_kex_should_not_raise_exception
assert_equal %w[diffie-hellman-group1-sha1] + ec_kex + %w[diffie-hellman-group-exchange-sha256 diffie-hellman-group-exchange-sha1 diffie-hellman-group14-sha1], algorithms(
kex: %w[bogus diffie-hellman-group1-sha1],append_all_supported_algorithms: true
)[:kex]
end
def test_constructor_with_preferred_encryption_should_put_preferred_encryption_first
assert_equal %w[aes256-cbc aes256-ctr aes192-ctr aes128-ctr aes192-cbc aes128-cbc rijndael-cbc@lysator.liu.se blowfish-ctr blowfish-cbc cast128-ctr cast128-cbc 3des-ctr 3des-cbc idea-cbc none], algorithms(encryption: "aes256-cbc",
append_all_supported_algorithms: true)[:encryption]
end
def test_constructor_with_multiple_preferred_encryption_should_put_all_preferred_encryption_first
assert_equal %w[aes256-cbc 3des-cbc idea-cbc aes256-ctr aes192-ctr aes128-ctr aes192-cbc aes128-cbc rijndael-cbc@lysator.liu.se blowfish-ctr blowfish-cbc cast128-ctr cast128-cbc 3des-ctr none], algorithms(encryption: %w[aes256-cbc 3des-cbc idea-cbc], append_all_supported_algorithms: true)[:encryption]
end
def test_constructor_with_unrecognized_encryption_should_keep_whats_supported
assert_equal %w[aes256-cbc aes256-ctr aes192-ctr aes128-ctr aes192-cbc aes128-cbc rijndael-cbc@lysator.liu.se blowfish-ctr blowfish-cbc cast128-ctr cast128-cbc 3des-ctr 3des-cbc idea-cbc none], algorithms(encryption: %w[bogus aes256-cbc], append_all_supported_algorithms: true)[:encryption]
end
def test_constructor_with_preferred_hmac_should_put_preferred_hmac_first
assert_equal %w[hmac-md5-96 hmac-sha2-512 hmac-sha2-256 hmac-sha2-512-96 hmac-sha2-256-96 hmac-sha1 hmac-sha1-96 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 none], algorithms(hmac: "hmac-md5-96", append_all_supported_algorithms: true)[:hmac]
end
def test_constructor_with_multiple_preferred_hmac_should_put_all_preferred_hmac_first
assert_equal %w[hmac-md5-96 hmac-sha1-96 hmac-sha2-512 hmac-sha2-256 hmac-sha2-512-96 hmac-sha2-256-96 hmac-sha1 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 none], algorithms(hmac: %w[hmac-md5-96 hmac-sha1-96], append_all_supported_algorithms: true)[:hmac]
end
def test_constructor_with_unrecognized_hmac_should_ignore_those
assert_equal %w[hmac-sha2-512 hmac-sha2-256 hmac-sha2-512-96 hmac-sha2-256-96 hmac-sha1 hmac-sha1-96 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 hmac-md5-96 none],
algorithms(hmac: "unknown hmac-md5-96", append_all_supported_algorithms: true)[:hmac]
end
def test_constructor_with_preferred_compression_should_put_preferred_compression_first
assert_equal %w[zlib none zlib@openssh.com], algorithms(compression: "zlib", append_all_supported_algorithms: true)[:compression]
end
def test_constructor_with_multiple_preferred_compression_should_put_all_preferred_compression_first
assert_equal %w[zlib@openssh.com zlib none], algorithms(compression: %w[zlib@openssh.com zlib],
append_all_supported_algorithms: true)[:compression]
end
def test_constructor_with_general_preferred_compression_should_put_none_last
assert_equal %w[zlib@openssh.com zlib none], algorithms(
compression: true, append_all_supported_algorithms: true
)[:compression]
end
def test_constructor_with_unrecognized_compression_should_return_whats_supported
assert_equal %w[none zlib zlib@openssh.com], algorithms(compression: %w[bogus none zlib], append_all_supported_algorithms: true)[:compression]
end
def test_constructor_with_append_to_default
default_host_keys = Net::SSH::Transport::Algorithms::ALGORITHMS[:host_key]
assert_equal default_host_keys, algorithms(host_key: '+ssh-dss')[:host_key]
end
def test_initial_state_should_be_neither_pending_nor_initialized
assert !algorithms.pending?
assert !algorithms.initialized?
end
def test_key_exchange_when_initiated_by_server
transport.expect do |t, buffer|
assert_kexinit(buffer)
install_mock_key_exchange(buffer)
end
install_mock_algorithm_lookups
algorithms.accept_kexinit(kexinit)
assert_exchange_results
end
def test_key_exchange_when_initiated_by_client
state = nil
transport.expect do |t, buffer|
assert_kexinit(buffer)
state = :sent_kexinit
install_mock_key_exchange(buffer)
end
algorithms.rekey!
assert_equal state, :sent_kexinit
assert algorithms.pending?
install_mock_algorithm_lookups
algorithms.accept_kexinit(kexinit)
assert_exchange_results
end
def test_key_exchange_when_server_does_not_support_preferred_kex_should_fallback_to_secondary
kexinit kex: "diffie-hellman-group1-sha1"
transport.expect do |t,buffer|
assert_kexinit(buffer)
install_mock_key_exchange(buffer, kex: Net::SSH::Transport::Kex::DiffieHellmanGroup1SHA1)
end
algorithms.accept_kexinit(kexinit)
end
def test_key_exchange_when_server_does_not_support_any_preferred_kex_should_raise_error
kexinit kex: "something-obscure"
transport.expect { |t,buffer| assert_kexinit(buffer) }
assert_raises(Net::SSH::Exception) { algorithms.accept_kexinit(kexinit) }
end
def test_allow_when_not_pending_should_be_true_for_all_packets
(0..255).each do |type|
packet = stub("packet", type: type)
assert algorithms.allow?(packet), type.to_s
end
end
def test_allow_when_pending_should_be_true_only_for_packets_valid_during_key_exchange
transport.expect!
algorithms.rekey!
assert algorithms.pending?
(0..255).each do |type|
packet = stub("packet", type: type)
case type
when 1..4, 6..19, 21..49 then assert(algorithms.allow?(packet), "#{type} should be allowed during key exchange")
else assert(!algorithms.allow?(packet), "#{type} should not be allowed during key exchange")
end
end
end
def test_exchange_with_zlib_compression_enabled_sets_compression_to_standard
algorithms compression: "zlib", append_all_supported_algorithms: true
transport.expect do |t, buffer|
assert_kexinit(buffer, compression_client: "zlib,none,zlib@openssh.com", compression_server: "zlib,none,zlib@openssh.com")
install_mock_key_exchange(buffer)
end
install_mock_algorithm_lookups
algorithms.accept_kexinit(kexinit)
assert_equal :standard, transport.client_options[:compression]
assert_equal :standard, transport.server_options[:compression]
end
def test_exchange_with_zlib_at_openssh_dot_com_compression_enabled_sets_compression_to_delayed
algorithms compression: "zlib@openssh.com", append_all_supported_algorithms: true
transport.expect do |t, buffer|
assert_kexinit(buffer, compression_client: "zlib@openssh.com,none,zlib", compression_server: "zlib@openssh.com,none,zlib")
install_mock_key_exchange(buffer)
end
install_mock_algorithm_lookups
algorithms.accept_kexinit(kexinit)
assert_equal :delayed, transport.client_options[:compression]
assert_equal :delayed, transport.server_options[:compression]
end
# Verification for https://github.com/net-ssh/net-ssh/issues/483
def test_that_algorithm_undefined_doesnt_throw_exception
# Create a logger explicitly with DEBUG logging
string_io = StringIO.new("")
debug_logger = Logger.new(string_io)
debug_logger.level = Logger::DEBUG
# Create our algorithm instance, with our logger sent to the underlying transport instance
alg = algorithms(
{},
logger: debug_logger
)
# Here are our two lists - "ours" and "theirs"
#
# [a,b] overlap
# [d] "unsupported" values
ours = %w[a b c]
theirs = %w[a b d]
## Hit the method directly
alg.send(
:compose_algorithm_list,
ours,
theirs
)
assert string_io.string.include?(%(unsupported algorithm: `["d"]'))
end
def test_host_key_format
algorithms(host_key: 'ssh-rsa-cert-v01@openssh.com').instance_eval { @host_key = 'ssh-rsa-cert-v01@openssh.com' }
assert_equal 'ssh-rsa', algorithms.host_key_format
end
private
def install_mock_key_exchange(buffer, options={})
kex = options[:kex] || Net::SSH::Transport::Kex::DiffieHellmanGroupExchangeSHA256
Net::SSH::Transport::Kex::MAP.each do |name, klass|
next if klass == kex
klass.expects(:new).never
end
kex.expects(:new)
.with(algorithms, transport,
client_version_string: Net::SSH::Transport::ServerVersion::PROTO_VERSION,
server_version_string: transport.server_version.version,
server_algorithm_packet: kexinit.to_s,
client_algorithm_packet: buffer.to_s,
need_bytes: 32,
minimum_dh_bits: nil,
logger: nil)
.returns(stub("kex", exchange_keys: { shared_secret: shared_secret, session_id: session_id, hashing_algorithm: hashing_algorithm }))
end
def install_mock_algorithm_lookups(options={})
params = { shared: shared_secret.to_ssh, hash: session_id, digester: hashing_algorithm }
Net::SSH::Transport::CipherFactory.expects(:get)
.with(options[:client_cipher] || "aes256-ctr", params.merge(iv: key("A"), key: key("C"), encrypt: true))
.returns(:client_cipher)
Net::SSH::Transport::CipherFactory.expects(:get)
.with(options[:server_cipher] || "aes256-ctr", params.merge(iv: key("B"), key: key("D"), decrypt: true))
.returns(:server_cipher)
Net::SSH::Transport::HMAC.expects(:get).with(options[:client_hmac] || "hmac-sha2-256", key("E"), params).returns(:client_hmac)
Net::SSH::Transport::HMAC.expects(:get).with(options[:server_hmac] || "hmac-sha2-256", key("F"), params).returns(:server_hmac)
end
def shared_secret
@shared_secret ||= OpenSSL::BN.new("1234567890", 10)
end
def session_id
@session_id ||= "this is the session id"
end
def hashing_algorithm
OpenSSL::Digest::SHA1
end
def key(salt)
hashing_algorithm.digest(shared_secret.to_ssh + session_id + salt + session_id)
end
def cipher(type, options={})
Net::SSH::Transport::CipherFactory.get(type, options)
end
def kexinit(options={})
@kexinit ||= P(:byte, KEXINIT,
:long, rand(0xFFFFFFFF), :long, rand(0xFFFFFFFF), :long, rand(0xFFFFFFFF), :long, rand(0xFFFFFFFF),
:string, options[:kex] || "diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1",
:string, options[:host_key] || "ssh-rsa,ssh-dss",
:string, options[:encryption_client] || "aes256-ctr,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,idea-cbc",
:string, options[:encryption_server] || "aes256-ctr,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,idea-cbc",
:string, options[:hmac_client] || "hmac-sha2-256,hmac-sha1,hmac-md5,hmac-sha1-96,hmac-md5-96",
:string, options[:hmac_server] || "hmac-sha2-256,hmac-sha1,hmac-md5,hmac-sha1-96,hmac-md5-96",
:string, options[:compression_client] || "none,zlib@openssh.com,zlib",
:string, options[:compression_server] || "none,zlib@openssh.com,zlib",
:string, options[:language_client] || "",
:string, options[:language_server] || "",
:bool, options[:first_kex_follows])
end
def assert_kexinit(buffer, options={})
assert_equal KEXINIT, buffer.type
assert_equal 16, buffer.read(16).length
assert_equal options[:kex] || (ec_kex + %w[diffie-hellman-group-exchange-sha256 diffie-hellman-group-exchange-sha1 diffie-hellman-group14-sha1 diffie-hellman-group1-sha1]).join(','), buffer.read_string
assert_equal options[:host_key] || (ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa ssh-dss]).join(','), buffer.read_string
assert_equal options[:encryption_client] || "aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,rijndael-cbc@lysator.liu.se,blowfish-ctr,blowfish-cbc,cast128-ctr,cast128-cbc,3des-ctr,3des-cbc,idea-cbc,none", buffer.read_string
assert_equal options[:encryption_server] || "aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,rijndael-cbc@lysator.liu.se,blowfish-ctr,blowfish-cbc,cast128-ctr,cast128-cbc,3des-ctr,3des-cbc,idea-cbc,none", buffer.read_string
assert_equal options[:hmac_client] || "hmac-sha2-512,hmac-sha2-256,hmac-sha2-512-96,hmac-sha2-256-96,hmac-sha1,hmac-sha1-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-md5,hmac-md5-96,none", buffer.read_string
assert_equal options[:hmac_server] || "hmac-sha2-512,hmac-sha2-256,hmac-sha2-512-96,hmac-sha2-256-96,hmac-sha1,hmac-sha1-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-md5,hmac-md5-96,none", buffer.read_string
assert_equal options[:compression_client] || "none,zlib@openssh.com,zlib", buffer.read_string
assert_equal options[:compression_server] || "none,zlib@openssh.com,zlib", buffer.read_string
assert_equal options[:language_client] || "", buffer.read_string
assert_equal options[:language_server] || "", buffer.read_string
assert_equal options[:first_kex_follows] || false, buffer.read_bool
end
def assert_exchange_results
assert algorithms.initialized?
assert !algorithms.pending?
assert !transport.client_options[:compression]
assert !transport.server_options[:compression]
assert_equal :client_cipher, transport.client_options[:cipher]
assert_equal :server_cipher, transport.server_options[:cipher]
assert_equal :client_hmac, transport.client_options[:hmac]
assert_equal :server_hmac, transport.server_options[:hmac]
end
def algorithms(algrothms_options={}, transport_options={})
@algorithms ||= Net::SSH::Transport::Algorithms.new(
transport(transport_options),
algrothms_options
)
end
def transport(transport_options={})
@transport ||= MockTransport.new(transport_options)
end
end
end
fix formatting issue to test_algorithms.rb
require_relative '../common'
require 'logger'
require 'net/ssh/transport/algorithms'
module Transport
class TestAlgorithms < NetSSHTest
include Net::SSH::Transport::Constants
def test_allowed_packets
(0..255).each do |type|
packet = stub("packet", type: type)
case type
when 1..4, 6..19, 21..49 then assert(Net::SSH::Transport::Algorithms.allowed_packet?(packet), "#{type} should be allowed during key exchange")
else assert(!Net::SSH::Transport::Algorithms.allowed_packet?(packet), "#{type} should not be allowed during key exchange")
end
end
end
def test_constructor_should_build_default_list_of_preferred_algorithms
assert_equal ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa ssh-dss], algorithms[:host_key]
assert_equal ec_kex + %w[diffie-hellman-group-exchange-sha256 diffie-hellman-group-exchange-sha1 diffie-hellman-group14-sha1 diffie-hellman-group1-sha1], algorithms[:kex]
assert_equal %w[aes256-ctr aes192-ctr aes128-ctr aes256-cbc aes192-cbc aes128-cbc rijndael-cbc@lysator.liu.se blowfish-ctr blowfish-cbc cast128-ctr cast128-cbc 3des-ctr 3des-cbc idea-cbc none], algorithms[:encryption]
if defined?(OpenSSL::Digest::SHA256)
assert_equal %w[hmac-sha2-512 hmac-sha2-256 hmac-sha2-512-96 hmac-sha2-256-96 hmac-sha1 hmac-sha1-96 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 hmac-md5-96 none], algorithms[:hmac]
else
assert_equal %w[hmac-sha1 hmac-sha1-96 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 hmac-md5-96 none], algorithms[:hmac]
end
assert_equal %w[none zlib@openssh.com zlib], algorithms[:compression]
assert_equal %w[], algorithms[:language]
end
def test_constructor_should_set_client_and_server_prefs_identically
%w[encryption hmac compression language].each do |key|
assert_equal algorithms[key.to_sym], algorithms[:"#{key}_client"], key
assert_equal algorithms[key.to_sym], algorithms[:"#{key}_server"], key
end
end
def test_constructor_with_preferred_host_key_type_should_put_preferred_host_key_type_first
assert_equal %w[ssh-dss] + ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa], algorithms(host_key: "ssh-dss", append_all_supported_algorithms: true)[:host_key]
end
def test_constructor_with_known_hosts_reporting_known_host_key_should_use_that_host_key_type
Net::SSH::KnownHosts.expects(:search_for).with("net.ssh.test,127.0.0.1", {}).returns([stub("key", ssh_type: "ssh-dss")])
assert_equal %w[ssh-dss] + ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa], algorithms[:host_key]
end
def ed_host_keys
if Net::SSH::Authentication::ED25519Loader::LOADED
%w[ssh-ed25519-cert-v01@openssh.com ssh-ed25519]
else
[]
end
end
def ec_host_keys
if defined?(OpenSSL::PKey::EC)
%w[ecdsa-sha2-nistp521-cert-v01@openssh.com
ecdsa-sha2-nistp384-cert-v01@openssh.com
ecdsa-sha2-nistp256-cert-v01@openssh.com
ecdsa-sha2-nistp521
ecdsa-sha2-nistp384
ecdsa-sha2-nistp256]
else
[]
end
end
def ed_ec_host_keys
ed_host_keys + ec_host_keys
end
def test_constructor_with_unrecognized_host_key_type_should_return_whats_supported
assert_equal ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa ssh-dss], algorithms(host_key: "bogus ssh-rsa",append_all_supported_algorithms: true)[:host_key]
end
def ec_kex
if defined?(OpenSSL::PKey::EC)
%w[ecdh-sha2-nistp521 ecdh-sha2-nistp384 ecdh-sha2-nistp256]
else
[]
end
end
def test_constructor_with_preferred_kex_should_put_preferred_kex_first
assert_equal %w[diffie-hellman-group1-sha1] + ec_kex + %w[diffie-hellman-group-exchange-sha256 diffie-hellman-group-exchange-sha1 diffie-hellman-group14-sha1], algorithms(kex: "diffie-hellman-group1-sha1", append_all_supported_algorithms: true)[:kex]
end
def test_constructor_with_unrecognized_kex_should_not_raise_exception
assert_equal %w[diffie-hellman-group1-sha1] + ec_kex + %w[diffie-hellman-group-exchange-sha256 diffie-hellman-group-exchange-sha1 diffie-hellman-group14-sha1], algorithms(
kex: %w[bogus diffie-hellman-group1-sha1],append_all_supported_algorithms: true
)[:kex]
end
def test_constructor_with_preferred_encryption_should_put_preferred_encryption_first
assert_equal %w[aes256-cbc aes256-ctr aes192-ctr aes128-ctr aes192-cbc aes128-cbc rijndael-cbc@lysator.liu.se blowfish-ctr blowfish-cbc cast128-ctr cast128-cbc 3des-ctr 3des-cbc idea-cbc none], algorithms(encryption: "aes256-cbc", append_all_supported_algorithms: true)[:encryption]
end
def test_constructor_with_multiple_preferred_encryption_should_put_all_preferred_encryption_first
assert_equal %w[aes256-cbc 3des-cbc idea-cbc aes256-ctr aes192-ctr aes128-ctr aes192-cbc aes128-cbc rijndael-cbc@lysator.liu.se blowfish-ctr blowfish-cbc cast128-ctr cast128-cbc 3des-ctr none], algorithms(encryption: %w[aes256-cbc 3des-cbc idea-cbc], append_all_supported_algorithms: true)[:encryption]
end
def test_constructor_with_unrecognized_encryption_should_keep_whats_supported
assert_equal %w[aes256-cbc aes256-ctr aes192-ctr aes128-ctr aes192-cbc aes128-cbc rijndael-cbc@lysator.liu.se blowfish-ctr blowfish-cbc cast128-ctr cast128-cbc 3des-ctr 3des-cbc idea-cbc none], algorithms(encryption: %w[bogus aes256-cbc], append_all_supported_algorithms: true)[:encryption]
end
def test_constructor_with_preferred_hmac_should_put_preferred_hmac_first
assert_equal %w[hmac-md5-96 hmac-sha2-512 hmac-sha2-256 hmac-sha2-512-96 hmac-sha2-256-96 hmac-sha1 hmac-sha1-96 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 none], algorithms(hmac: "hmac-md5-96", append_all_supported_algorithms: true)[:hmac]
end
def test_constructor_with_multiple_preferred_hmac_should_put_all_preferred_hmac_first
assert_equal %w[hmac-md5-96 hmac-sha1-96 hmac-sha2-512 hmac-sha2-256 hmac-sha2-512-96 hmac-sha2-256-96 hmac-sha1 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 none], algorithms(hmac: %w[hmac-md5-96 hmac-sha1-96], append_all_supported_algorithms: true)[:hmac]
end
def test_constructor_with_unrecognized_hmac_should_ignore_those
assert_equal %w[hmac-sha2-512 hmac-sha2-256 hmac-sha2-512-96 hmac-sha2-256-96 hmac-sha1 hmac-sha1-96 hmac-ripemd160 hmac-ripemd160@openssh.com hmac-md5 hmac-md5-96 none],
algorithms(hmac: "unknown hmac-md5-96", append_all_supported_algorithms: true)[:hmac]
end
def test_constructor_with_preferred_compression_should_put_preferred_compression_first
assert_equal %w[zlib none zlib@openssh.com], algorithms(compression: "zlib", append_all_supported_algorithms: true)[:compression]
end
def test_constructor_with_multiple_preferred_compression_should_put_all_preferred_compression_first
assert_equal %w[zlib@openssh.com zlib none], algorithms(compression: %w[zlib@openssh.com zlib],
append_all_supported_algorithms: true)[:compression]
end
def test_constructor_with_general_preferred_compression_should_put_none_last
assert_equal %w[zlib@openssh.com zlib none], algorithms(
compression: true, append_all_supported_algorithms: true
)[:compression]
end
def test_constructor_with_unrecognized_compression_should_return_whats_supported
assert_equal %w[none zlib zlib@openssh.com], algorithms(compression: %w[bogus none zlib], append_all_supported_algorithms: true)[:compression]
end
def test_constructor_with_append_to_default
default_host_keys = Net::SSH::Transport::Algorithms::ALGORITHMS[:host_key]
assert_equal default_host_keys, algorithms(host_key: '+ssh-dss')[:host_key]
end
def test_initial_state_should_be_neither_pending_nor_initialized
assert !algorithms.pending?
assert !algorithms.initialized?
end
def test_key_exchange_when_initiated_by_server
transport.expect do |t, buffer|
assert_kexinit(buffer)
install_mock_key_exchange(buffer)
end
install_mock_algorithm_lookups
algorithms.accept_kexinit(kexinit)
assert_exchange_results
end
def test_key_exchange_when_initiated_by_client
state = nil
transport.expect do |t, buffer|
assert_kexinit(buffer)
state = :sent_kexinit
install_mock_key_exchange(buffer)
end
algorithms.rekey!
assert_equal state, :sent_kexinit
assert algorithms.pending?
install_mock_algorithm_lookups
algorithms.accept_kexinit(kexinit)
assert_exchange_results
end
def test_key_exchange_when_server_does_not_support_preferred_kex_should_fallback_to_secondary
kexinit kex: "diffie-hellman-group1-sha1"
transport.expect do |t,buffer|
assert_kexinit(buffer)
install_mock_key_exchange(buffer, kex: Net::SSH::Transport::Kex::DiffieHellmanGroup1SHA1)
end
algorithms.accept_kexinit(kexinit)
end
def test_key_exchange_when_server_does_not_support_any_preferred_kex_should_raise_error
kexinit kex: "something-obscure"
transport.expect { |t,buffer| assert_kexinit(buffer) }
assert_raises(Net::SSH::Exception) { algorithms.accept_kexinit(kexinit) }
end
def test_allow_when_not_pending_should_be_true_for_all_packets
(0..255).each do |type|
packet = stub("packet", type: type)
assert algorithms.allow?(packet), type.to_s
end
end
def test_allow_when_pending_should_be_true_only_for_packets_valid_during_key_exchange
transport.expect!
algorithms.rekey!
assert algorithms.pending?
(0..255).each do |type|
packet = stub("packet", type: type)
case type
when 1..4, 6..19, 21..49 then assert(algorithms.allow?(packet), "#{type} should be allowed during key exchange")
else assert(!algorithms.allow?(packet), "#{type} should not be allowed during key exchange")
end
end
end
def test_exchange_with_zlib_compression_enabled_sets_compression_to_standard
algorithms compression: "zlib", append_all_supported_algorithms: true
transport.expect do |t, buffer|
assert_kexinit(buffer, compression_client: "zlib,none,zlib@openssh.com", compression_server: "zlib,none,zlib@openssh.com")
install_mock_key_exchange(buffer)
end
install_mock_algorithm_lookups
algorithms.accept_kexinit(kexinit)
assert_equal :standard, transport.client_options[:compression]
assert_equal :standard, transport.server_options[:compression]
end
def test_exchange_with_zlib_at_openssh_dot_com_compression_enabled_sets_compression_to_delayed
algorithms compression: "zlib@openssh.com", append_all_supported_algorithms: true
transport.expect do |t, buffer|
assert_kexinit(buffer, compression_client: "zlib@openssh.com,none,zlib", compression_server: "zlib@openssh.com,none,zlib")
install_mock_key_exchange(buffer)
end
install_mock_algorithm_lookups
algorithms.accept_kexinit(kexinit)
assert_equal :delayed, transport.client_options[:compression]
assert_equal :delayed, transport.server_options[:compression]
end
# Verification for https://github.com/net-ssh/net-ssh/issues/483
def test_that_algorithm_undefined_doesnt_throw_exception
# Create a logger explicitly with DEBUG logging
string_io = StringIO.new("")
debug_logger = Logger.new(string_io)
debug_logger.level = Logger::DEBUG
# Create our algorithm instance, with our logger sent to the underlying transport instance
alg = algorithms(
{},
logger: debug_logger
)
# Here are our two lists - "ours" and "theirs"
#
# [a,b] overlap
# [d] "unsupported" values
ours = %w[a b c]
theirs = %w[a b d]
## Hit the method directly
alg.send(
:compose_algorithm_list,
ours,
theirs
)
assert string_io.string.include?(%(unsupported algorithm: `["d"]'))
end
def test_host_key_format
algorithms(host_key: 'ssh-rsa-cert-v01@openssh.com').instance_eval { @host_key = 'ssh-rsa-cert-v01@openssh.com' }
assert_equal 'ssh-rsa', algorithms.host_key_format
end
private
def install_mock_key_exchange(buffer, options={})
kex = options[:kex] || Net::SSH::Transport::Kex::DiffieHellmanGroupExchangeSHA256
Net::SSH::Transport::Kex::MAP.each do |name, klass|
next if klass == kex
klass.expects(:new).never
end
kex.expects(:new)
.with(algorithms, transport,
client_version_string: Net::SSH::Transport::ServerVersion::PROTO_VERSION,
server_version_string: transport.server_version.version,
server_algorithm_packet: kexinit.to_s,
client_algorithm_packet: buffer.to_s,
need_bytes: 32,
minimum_dh_bits: nil,
logger: nil)
.returns(stub("kex", exchange_keys: { shared_secret: shared_secret, session_id: session_id, hashing_algorithm: hashing_algorithm }))
end
def install_mock_algorithm_lookups(options={})
params = { shared: shared_secret.to_ssh, hash: session_id, digester: hashing_algorithm }
Net::SSH::Transport::CipherFactory.expects(:get)
.with(options[:client_cipher] || "aes256-ctr", params.merge(iv: key("A"), key: key("C"), encrypt: true))
.returns(:client_cipher)
Net::SSH::Transport::CipherFactory.expects(:get)
.with(options[:server_cipher] || "aes256-ctr", params.merge(iv: key("B"), key: key("D"), decrypt: true))
.returns(:server_cipher)
Net::SSH::Transport::HMAC.expects(:get).with(options[:client_hmac] || "hmac-sha2-256", key("E"), params).returns(:client_hmac)
Net::SSH::Transport::HMAC.expects(:get).with(options[:server_hmac] || "hmac-sha2-256", key("F"), params).returns(:server_hmac)
end
def shared_secret
@shared_secret ||= OpenSSL::BN.new("1234567890", 10)
end
def session_id
@session_id ||= "this is the session id"
end
def hashing_algorithm
OpenSSL::Digest::SHA1
end
def key(salt)
hashing_algorithm.digest(shared_secret.to_ssh + session_id + salt + session_id)
end
def cipher(type, options={})
Net::SSH::Transport::CipherFactory.get(type, options)
end
def kexinit(options={})
@kexinit ||= P(:byte, KEXINIT,
:long, rand(0xFFFFFFFF), :long, rand(0xFFFFFFFF), :long, rand(0xFFFFFFFF), :long, rand(0xFFFFFFFF),
:string, options[:kex] || "diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1",
:string, options[:host_key] || "ssh-rsa,ssh-dss",
:string, options[:encryption_client] || "aes256-ctr,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,idea-cbc",
:string, options[:encryption_server] || "aes256-ctr,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,rijndael-cbc@lysator.liu.se,idea-cbc",
:string, options[:hmac_client] || "hmac-sha2-256,hmac-sha1,hmac-md5,hmac-sha1-96,hmac-md5-96",
:string, options[:hmac_server] || "hmac-sha2-256,hmac-sha1,hmac-md5,hmac-sha1-96,hmac-md5-96",
:string, options[:compression_client] || "none,zlib@openssh.com,zlib",
:string, options[:compression_server] || "none,zlib@openssh.com,zlib",
:string, options[:language_client] || "",
:string, options[:language_server] || "",
:bool, options[:first_kex_follows])
end
def assert_kexinit(buffer, options={})
assert_equal KEXINIT, buffer.type
assert_equal 16, buffer.read(16).length
assert_equal options[:kex] || (ec_kex + %w[diffie-hellman-group-exchange-sha256 diffie-hellman-group-exchange-sha1 diffie-hellman-group14-sha1 diffie-hellman-group1-sha1]).join(','), buffer.read_string
assert_equal options[:host_key] || (ed_ec_host_keys + %w[ssh-rsa-cert-v01@openssh.com ssh-rsa-cert-v00@openssh.com ssh-rsa ssh-dss]).join(','), buffer.read_string
assert_equal options[:encryption_client] || "aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,rijndael-cbc@lysator.liu.se,blowfish-ctr,blowfish-cbc,cast128-ctr,cast128-cbc,3des-ctr,3des-cbc,idea-cbc,none", buffer.read_string
assert_equal options[:encryption_server] || "aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc,rijndael-cbc@lysator.liu.se,blowfish-ctr,blowfish-cbc,cast128-ctr,cast128-cbc,3des-ctr,3des-cbc,idea-cbc,none", buffer.read_string
assert_equal options[:hmac_client] || "hmac-sha2-512,hmac-sha2-256,hmac-sha2-512-96,hmac-sha2-256-96,hmac-sha1,hmac-sha1-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-md5,hmac-md5-96,none", buffer.read_string
assert_equal options[:hmac_server] || "hmac-sha2-512,hmac-sha2-256,hmac-sha2-512-96,hmac-sha2-256-96,hmac-sha1,hmac-sha1-96,hmac-ripemd160,hmac-ripemd160@openssh.com,hmac-md5,hmac-md5-96,none", buffer.read_string
assert_equal options[:compression_client] || "none,zlib@openssh.com,zlib", buffer.read_string
assert_equal options[:compression_server] || "none,zlib@openssh.com,zlib", buffer.read_string
assert_equal options[:language_client] || "", buffer.read_string
assert_equal options[:language_server] || "", buffer.read_string
assert_equal options[:first_kex_follows] || false, buffer.read_bool
end
def assert_exchange_results
assert algorithms.initialized?
assert !algorithms.pending?
assert !transport.client_options[:compression]
assert !transport.server_options[:compression]
assert_equal :client_cipher, transport.client_options[:cipher]
assert_equal :server_cipher, transport.server_options[:cipher]
assert_equal :client_hmac, transport.client_options[:hmac]
assert_equal :server_hmac, transport.server_options[:hmac]
end
def algorithms(algrothms_options={}, transport_options={})
@algorithms ||= Net::SSH::Transport::Algorithms.new(
transport(transport_options),
algrothms_options
)
end
def transport(transport_options={})
@transport ||= MockTransport.new(transport_options)
end
end
end
|
require File.dirname(__FILE__) + '/../test_helper'
class ApproveArticleTest < ActiveSupport::TestCase
def setup
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@profile = create_user('test_user').person
@article = fast_create(TextileArticle, :profile_id => @profile.id, :name => 'test name', :abstract => 'Lead of article', :body => 'This is my article')
@community = fast_create(Community)
end
attr_reader :profile, :article, :community
should 'have name, reference article and profile' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
assert_equal article, a.article
assert_equal community, a.target
end
should 'have abstract and body' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
assert_equal ['Lead of article', 'This is my article'], [a.abstract, a.body]
end
should 'create an article with the same class as original when finished' do
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
a.finish
end
end
should 'override target notification message method from Task' do
p1 = profile
p2 = create_user('testuser2').person
task = AddFriend.new(:person => p1, :friend => p2)
assert_nothing_raised NotImplementedError do
task.target_notification_message
end
end
should 'have parent if defined' do
folder = profile.articles.create!(:name => 'test folder', :type => 'Folder')
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => profile, :requestor => profile, :article_parent_id => folder.id)
assert_equal folder, a.article_parent
end
should 'not have parent if not defined' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => profile, :requestor => profile)
assert_nil a.article_parent
end
should 'alert when reference article is removed' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => profile, :requestor => profile)
article.destroy
a.reload
assert_equal "The article was removed.", a.information[:message]
end
should 'preserve article_parent' do
a = ApproveArticle.new(:article_parent => article)
assert_equal article, a.article_parent
end
should 'handle blank names' do
a = ApproveArticle.create!(:name => '', :article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
a.finish
end
end
should 'notify target if group is moderated' do
community.moderated_articles = true
community.save
community.stubs(:notification_emails).returns(['adm@example.com'])
a = ApproveArticle.create!(:name => '', :article => article, :target => community, :requestor => profile)
assert !ActionMailer::Base.deliveries.empty?
end
should 'not notify target if group is not moderated' do
community.moderated_articles = false
community.save
a = ApproveArticle.create!(:name => '', :article => article, :target => community, :requestor => profile)
assert ActionMailer::Base.deliveries.empty?
end
should 'copy the source from the original article' do
article.source = 'sample-feed.com'
article.save
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
assert_equal article.class.last.source, article.source
end
should 'have a reference article and profile on published article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
published = article.class.last
assert_equal [article, community], [published.reference_article, published.profile]
end
should 'copy name from original article' do
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal 'test name', article.class.last.name
end
should 'be able to edit name of generated article' do
a = ApproveArticle.create!(:name => 'Other name', :article => article, :target => community, :requestor => profile)
a.abstract = 'Abstract edited';a.save
a.finish
assert_equal 'Other name', article.class.last.name
end
should 'copy abstract from original article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
assert_equal 'Lead of article', article.class.last.abstract
end
should 'be able to edit abstract of generated article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.abstract = 'Abstract edited';a.save
a.finish
assert_equal 'Abstract edited', article.class.last.abstract
end
should 'copy body from original article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
assert_equal 'This is my article', article.class.last.body
end
should 'be able to edit body of generated article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.body = 'Body edited';a.save
a.finish
assert_equal 'Body edited', article.class.last.body
end
should 'not be created in blog if community does not have a blog' do
profile_blog = fast_create(Blog, :profile_id => profile.id)
article.parent = profile_blog
article.save
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert !community.has_blog?
assert_nil article.class.last.parent
end
should 'be created in community blog if came from a blog' do
profile_blog = fast_create(Blog, :profile_id => profile.id)
article.parent = profile_blog
article.save
community.articles << Blog.new(:profile => community)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal community.blog, article.class.last.parent
end
should 'not be created in community blog if did not come from a blog' do
profile_folder = fast_create(Folder, :profile_id => profile.id)
article.parent = profile_folder
article.save
blog = fast_create(Blog, :profile_id => community.id)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_nil article.class.last.parent
end
should 'overwrite blog if parent was choosen on published' do
profile_blog = fast_create(Blog, :profile_id => profile.id)
article.parent = profile_blog
article.save
community.articles << Blog.new(:profile => community)
community_folder = fast_create(Folder, :profile_id => profile.id)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile, :article_parent => community_folder)
a.finish
assert_equal community_folder, article.class.last.parent
end
should 'use author from original article on published' do
article.class.any_instance.stubs(:author).returns(profile)
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
assert_equal profile, article.class.last.author
end
should 'use original article author even if article is destroyed' do
article.class.any_instance.stubs(:author).returns(profile)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
article.destroy
assert_equal profile, article.class.last.author
end
should 'the published article have parent if defined' do
folder = fast_create(Folder, :profile_id => community.id)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile, :article_parent => folder)
a.finish
assert_equal folder, article.class.last.parent
end
should 'copy to_html from reference_article' do
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal article.to_html, article.class.last.to_html
end
should 'notify activity on creating published' do
ActionTracker::Record.delete_all
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal 1, ActionTracker::Record.count
end
should 'not group trackers activity of article\'s creation' do
ActionTracker::Record.delete_all
article = fast_create(TextileArticle)
a = ApproveArticle.create!(:name => 'bar', :article => article, :target => community, :requestor => profile)
a.finish
article = fast_create(TextileArticle)
a = ApproveArticle.create!(:name => 'another bar', :article => article, :target => community, :requestor => profile)
a.finish
article = fast_create(TextileArticle)
other_community = fast_create(Community)
a = ApproveArticle.create!(:name => 'another bar', :article => article, :target => other_community, :requestor => profile)
a.finish
assert_equal 3, ActionTracker::Record.count
end
should 'not create trackers activity when updating articles' do
ActionTracker::Record.delete_all
article1 = fast_create(TextileArticle)
a = ApproveArticle.create!(:name => 'bar', :article => article1, :target => community, :requestor => profile)
a.finish
article2 = fast_create(TinyMceArticle)
other_community = fast_create(Community)
a = ApproveArticle.create!(:name => 'another bar', :article => article2, :target => other_community, :requestor => profile)
a.finish
assert_equal 2, ActionTracker::Record.count
assert_no_difference ActionTracker::Record, :count do
published = article1.class.last
published.name = 'foo';published.save!
published = article2.class.last
published.name = 'another foo';published.save!
end
end
should "the tracker action target be defined as the article on articles'creation in communities" do
ActionTracker::Record.delete_all
person = fast_create(Person)
community.add_member(person)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
approved_article = community.articles.find_by_name(article.name)
assert_equal approved_article, ActionTracker::Record.last.target
end
should "the tracker action target be defined as the article on articles'creation in profile" do
ActionTracker::Record.delete_all
person = fast_create(Person)
a = ApproveArticle.create!(:article => article, :target => person, :requestor => profile)
a.finish
approved_article = person.articles.find_by_name(article.name)
assert_equal approved_article, ActionTracker::Record.last.target
end
should "have the same is_trackable method as original article" do
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal article.is_trackable?, article.class.last.is_trackable?
end
should 'not have target notification message if it is not a moderated oganization' do
community.moderated_articles = false; community.save
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
assert_nil task.target_notification_message
end
should 'have target notification message if is organization and not moderated' do
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
community.expects(:moderated_articles?).returns(['true'])
assert_match(/wants to publish the article.*[\n]*.*to approve or reject/, task.target_notification_message)
end
should 'have target notification description' do
community.moderated_articles = false; community.save
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
assert_match(/#{task.requestor.name} wants to publish the article: #{article.name}/, task.target_notification_description)
end
should 'deliver target notification message' do
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
community.expects(:notification_emails).returns(['target@example.com'])
community.expects(:moderated_articles?).returns(['true'])
email = TaskMailer.deliver_target_notification(task, task.target_notification_message)
assert_match(/#{task.requestor.name} wants to publish the article: #{article.name}/, email.subject)
end
should 'deliver target finished message' do
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
email = TaskMailer.deliver_task_finished(task)
assert_match(/#{task.requestor.name} wants to publish the article: #{article.name}/, email.subject)
end
should 'deliver target finished message about article deleted' do
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
article.destroy
email = TaskMailer.deliver_task_finished(task)
assert_match(/#{task.requestor.name} wanted to publish an article but it was removed/, email.subject)
end
should 'approve an event' do
event = fast_create(Event, :profile_id => profile.id, :name => 'Event test', :slug => 'event-test', :abstract => 'Lead of article', :body => 'This is my event')
task = ApproveArticle.create!(:name => 'Event test', :article => event, :target => community, :requestor => profile)
assert_difference event.class, :count do
task.finish
end
end
should 'approve same article twice changing its name' do
task1 = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
task1.finish
end
task2 = ApproveArticle.create!(:name => article.name + ' v2', :article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
assert_nothing_raised ActiveRecord::RecordInvalid do
task2.finish
end
end
end
should 'not approve same article twice if not changing its name' do
task1 = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
task1.finish
end
task2 = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
assert_no_difference article.class, :count do
assert_raises ActiveRecord::RecordInvalid do
task2.finish
end
end
end
should 'return reject message even without reject explanation' do
task = ApproveArticle.new(:name => 'My Article')
assert_not_nil task.task_cancelled_message
end
should 'show the name of the article in the reject message' do
task = ApproveArticle.new(:name => 'My Article')
assert_match /My Article/, task.task_cancelled_message
end
end
Testing article approval with an article that has a nil author
require File.dirname(__FILE__) + '/../test_helper'
class ApproveArticleTest < ActiveSupport::TestCase
def setup
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@profile = create_user('test_user').person
@article = fast_create(TextileArticle, :profile_id => @profile.id, :name => 'test name', :abstract => 'Lead of article', :body => 'This is my article')
@community = fast_create(Community)
end
attr_reader :profile, :article, :community
should 'have name, reference article and profile' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
assert_equal article, a.article
assert_equal community, a.target
end
should 'have abstract and body' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
assert_equal ['Lead of article', 'This is my article'], [a.abstract, a.body]
end
should 'create an article with the same class as original when finished' do
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
a.finish
end
end
should 'override target notification message method from Task' do
p1 = profile
p2 = create_user('testuser2').person
task = AddFriend.new(:person => p1, :friend => p2)
assert_nothing_raised NotImplementedError do
task.target_notification_message
end
end
should 'have parent if defined' do
folder = profile.articles.create!(:name => 'test folder', :type => 'Folder')
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => profile, :requestor => profile, :article_parent_id => folder.id)
assert_equal folder, a.article_parent
end
should 'not have parent if not defined' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => profile, :requestor => profile)
assert_nil a.article_parent
end
should 'alert when reference article is removed' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => profile, :requestor => profile)
article.destroy
a.reload
assert_equal "The article was removed.", a.information[:message]
end
should 'preserve article_parent' do
a = ApproveArticle.new(:article_parent => article)
assert_equal article, a.article_parent
end
should 'handle blank names' do
a = ApproveArticle.create!(:name => '', :article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
a.finish
end
end
should 'notify target if group is moderated' do
community.moderated_articles = true
community.save
community.stubs(:notification_emails).returns(['adm@example.com'])
a = ApproveArticle.create!(:name => '', :article => article, :target => community, :requestor => profile)
assert !ActionMailer::Base.deliveries.empty?
end
should 'not notify target if group is not moderated' do
community.moderated_articles = false
community.save
a = ApproveArticle.create!(:name => '', :article => article, :target => community, :requestor => profile)
assert ActionMailer::Base.deliveries.empty?
end
should 'copy the source from the original article' do
article.source = 'sample-feed.com'
article.save
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
assert_equal article.class.last.source, article.source
end
should 'have a reference article and profile on published article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
published = article.class.last
assert_equal [article, community], [published.reference_article, published.profile]
end
should 'copy name from original article' do
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal 'test name', article.class.last.name
end
should 'be able to edit name of generated article' do
a = ApproveArticle.create!(:name => 'Other name', :article => article, :target => community, :requestor => profile)
a.abstract = 'Abstract edited';a.save
a.finish
assert_equal 'Other name', article.class.last.name
end
should 'copy abstract from original article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
assert_equal 'Lead of article', article.class.last.abstract
end
should 'be able to edit abstract of generated article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.abstract = 'Abstract edited';a.save
a.finish
assert_equal 'Abstract edited', article.class.last.abstract
end
should 'copy body from original article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
assert_equal 'This is my article', article.class.last.body
end
should 'be able to edit body of generated article' do
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.body = 'Body edited';a.save
a.finish
assert_equal 'Body edited', article.class.last.body
end
should 'not be created in blog if community does not have a blog' do
profile_blog = fast_create(Blog, :profile_id => profile.id)
article.parent = profile_blog
article.save
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert !community.has_blog?
assert_nil article.class.last.parent
end
should 'be created in community blog if came from a blog' do
profile_blog = fast_create(Blog, :profile_id => profile.id)
article.parent = profile_blog
article.save
community.articles << Blog.new(:profile => community)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal community.blog, article.class.last.parent
end
should 'not be created in community blog if did not come from a blog' do
profile_folder = fast_create(Folder, :profile_id => profile.id)
article.parent = profile_folder
article.save
blog = fast_create(Blog, :profile_id => community.id)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_nil article.class.last.parent
end
should 'overwrite blog if parent was choosen on published' do
profile_blog = fast_create(Blog, :profile_id => profile.id)
article.parent = profile_blog
article.save
community.articles << Blog.new(:profile => community)
community_folder = fast_create(Folder, :profile_id => profile.id)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile, :article_parent => community_folder)
a.finish
assert_equal community_folder, article.class.last.parent
end
should 'use author from original article on published' do
article.class.any_instance.stubs(:author).returns(profile)
a = ApproveArticle.create!(:name => 'test name', :article => article, :target => community, :requestor => profile)
a.finish
assert_equal profile, article.class.last.author
end
should 'use original article author even if article is destroyed' do
article.class.any_instance.stubs(:author).returns(profile)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
article.destroy
assert_equal profile, article.class.last.author
end
should 'the published article have parent if defined' do
folder = fast_create(Folder, :profile_id => community.id)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile, :article_parent => folder)
a.finish
assert_equal folder, article.class.last.parent
end
should 'copy to_html from reference_article' do
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal article.to_html, article.class.last.to_html
end
should 'notify activity on creating published' do
ActionTracker::Record.delete_all
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal 1, ActionTracker::Record.count
end
should 'not group trackers activity of article\'s creation' do
ActionTracker::Record.delete_all
article = fast_create(TextileArticle)
a = ApproveArticle.create!(:name => 'bar', :article => article, :target => community, :requestor => profile)
a.finish
article = fast_create(TextileArticle)
a = ApproveArticle.create!(:name => 'another bar', :article => article, :target => community, :requestor => profile)
a.finish
article = fast_create(TextileArticle)
other_community = fast_create(Community)
a = ApproveArticle.create!(:name => 'another bar', :article => article, :target => other_community, :requestor => profile)
a.finish
assert_equal 3, ActionTracker::Record.count
end
should 'not create trackers activity when updating articles' do
ActionTracker::Record.delete_all
article1 = fast_create(TextileArticle)
a = ApproveArticle.create!(:name => 'bar', :article => article1, :target => community, :requestor => profile)
a.finish
article2 = fast_create(TinyMceArticle)
other_community = fast_create(Community)
a = ApproveArticle.create!(:name => 'another bar', :article => article2, :target => other_community, :requestor => profile)
a.finish
assert_equal 2, ActionTracker::Record.count
assert_no_difference ActionTracker::Record, :count do
published = article1.class.last
published.name = 'foo';published.save!
published = article2.class.last
published.name = 'another foo';published.save!
end
end
should "the tracker action target be defined as the article on articles'creation in communities" do
ActionTracker::Record.delete_all
person = fast_create(Person)
community.add_member(person)
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
approved_article = community.articles.find_by_name(article.name)
assert_equal approved_article, ActionTracker::Record.last.target
end
should "the tracker action target be defined as the article on articles'creation in profile" do
ActionTracker::Record.delete_all
person = fast_create(Person)
a = ApproveArticle.create!(:article => article, :target => person, :requestor => profile)
a.finish
approved_article = person.articles.find_by_name(article.name)
assert_equal approved_article, ActionTracker::Record.last.target
end
should "have the same is_trackable method as original article" do
a = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
a.finish
assert_equal article.is_trackable?, article.class.last.is_trackable?
end
should 'not have target notification message if it is not a moderated oganization' do
community.moderated_articles = false; community.save
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
assert_nil task.target_notification_message
end
should 'have target notification message if is organization and not moderated' do
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
community.expects(:moderated_articles?).returns(['true'])
assert_match(/wants to publish the article.*[\n]*.*to approve or reject/, task.target_notification_message)
end
should 'have target notification description' do
community.moderated_articles = false; community.save
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
assert_match(/#{task.requestor.name} wants to publish the article: #{article.name}/, task.target_notification_description)
end
should 'deliver target notification message' do
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
community.expects(:notification_emails).returns(['target@example.com'])
community.expects(:moderated_articles?).returns(['true'])
email = TaskMailer.deliver_target_notification(task, task.target_notification_message)
assert_match(/#{task.requestor.name} wants to publish the article: #{article.name}/, email.subject)
end
should 'deliver target finished message' do
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
email = TaskMailer.deliver_task_finished(task)
assert_match(/#{task.requestor.name} wants to publish the article: #{article.name}/, email.subject)
end
should 'deliver target finished message about article deleted' do
task = ApproveArticle.new(:article => article, :target => community, :requestor => profile)
article.destroy
email = TaskMailer.deliver_task_finished(task)
assert_match(/#{task.requestor.name} wanted to publish an article but it was removed/, email.subject)
end
should 'approve an event' do
event = fast_create(Event, :profile_id => profile.id, :name => 'Event test', :slug => 'event-test', :abstract => 'Lead of article', :body => 'This is my event')
task = ApproveArticle.create!(:name => 'Event test', :article => event, :target => community, :requestor => profile)
assert_difference event.class, :count do
task.finish
end
end
should 'approve same article twice changing its name' do
task1 = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
task1.finish
end
task2 = ApproveArticle.create!(:name => article.name + ' v2', :article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
assert_nothing_raised ActiveRecord::RecordInvalid do
task2.finish
end
end
end
should 'not approve same article twice if not changing its name' do
task1 = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
assert_difference article.class, :count do
task1.finish
end
task2 = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
assert_no_difference article.class, :count do
assert_raises ActiveRecord::RecordInvalid do
task2.finish
end
end
end
should 'return reject message even without reject explanation' do
task = ApproveArticle.new(:name => 'My Article')
assert_not_nil task.task_cancelled_message
end
should 'show the name of the article in the reject message' do
task = ApproveArticle.new(:name => 'My Article')
assert_match /My Article/, task.task_cancelled_message
end
should 'not save 4 on the new article\'s last_changed_by_ud after approval if author is nil' do
article = fast_create(Article)
task = ApproveArticle.create!(:article => article, :target => community, :requestor => profile)
task.finish
new_article = Article.last
assert_nil new_article.last_changed_by_id
end
end
|
require File.dirname(__FILE__) + '/../test_helper'
class LayoutTemplateTest < ActiveSupport::TestCase
should 'read configuration' do
YAML.expects(:load_file).with(Rails.root + '/public/designs/templates/default/config.yml').returns({'number_of_boxes' => 3, 'description' => 'my description', 'title' => 'my title'})
t = LayoutTemplate.find('default')
assert_equal 3, t.number_of_boxes
assert_equal 'my description', t.description
assert_equal 'my title', t.title
end
should 'list all' do
Dir.expects(:glob).with(Rails.root + '/public/designs/templates/*').returns([Rails.root + '/public/designs/templates/one', Rails.root + '/public/designs/templates/two'])
YAML.expects(:load_file).with(Rails.root + '/public/designs/templates/one/config.yml').returns({})
YAML.expects(:load_file).with(Rails.root + '/public/designs/templates/two/config.yml').returns({})
all = LayoutTemplate.all
assert_equivalent [ 'one', 'two' ], all.map(&:id)
end
end
rails3: Rails.root is not a string anymore
require File.dirname(__FILE__) + '/../test_helper'
class LayoutTemplateTest < ActiveSupport::TestCase
should 'read configuration' do
YAML.expects(:load_file).with(File.join(Rails.root, 'public/designs/templates/default/config.yml')).returns({'number_of_boxes' => 3, 'description' => 'my description', 'title' => 'my title'})
t = LayoutTemplate.find('default')
assert_equal 3, t.number_of_boxes
assert_equal 'my description', t.description
assert_equal 'my title', t.title
end
should 'list all' do
Dir.expects(:glob).with(File.join(Rails.root, 'public/designs/templates/*')).returns([File.join(Rails.root, 'public/designs/templates/one'), File.join(Rails.root, 'public/designs/templates/two')])
YAML.expects(:load_file).with(File.join(Rails.root, 'public/designs/templates/one/config.yml')).returns({})
YAML.expects(:load_file).with(File.join(Rails.root, 'public/designs/templates/two/config.yml')).returns({})
all = LayoutTemplate.all
assert_equivalent [ 'one', 'two' ], all.map(&:id)
end
end
|
# Encoding: UTF-8
# Doesn't yet cover everything, but started it to cover new func we wrote at least
require 'test_helper'
class MetadataHelperTest < ActiveSupport::TestCase
include MetadataHelper
ContextObject = OpenURL::ContextObject
def test_get_search_title_i18n
co = ContextObject.new_from_kev("sid=google&auinit=R&aulast=Dunayevskaya&title=Filosofía.+y+revolución:+de+Hegel+a+Sartre+y+de+Marx+a+Mao")
assert_equal "filosofía y revolución", get_search_title(co.referent)
end
def test_get_isbn
co = ContextObject.new_from_kev("isbn=079284937X")
assert_equal "079284937X", get_isbn(co.referent)
co = ContextObject.new_from_kev("rft.isbn=079284937X")
assert_equal "079284937X", get_isbn(co.referent)
co = ContextObject.new_from_kev("isbn=0-435-08441-0")
assert_equal "0435084410", get_isbn(co.referent)
co = ContextObject.new_from_kev("isbn=0435084410+%28pbk.%29")
assert_equal "0435084410", get_isbn(co.referent)
end
def test_get_month
co = ContextObject.new_from_kev("date=2012-9-01&foo=bar")
assert_equal "9", get_month(co.referent)
co = ContextObject.new_from_kev("date=2012-10-01&foo=bar")
assert_equal "10", get_month(co.referent)
co = ContextObject.new_from_kev("date=2012-10&foo=bar")
assert_equal "10", get_month(co.referent)
co = ContextObject.new_from_kev("date=2012-10-01&month=9")
assert_equal "10", get_month(co.referent)
# If no date, try non-standard month
co = ContextObject.new_from_kev("month=9&foo=bar")
assert_equal "9", get_month(co.referent)
end
def test_get_spage
co = ContextObject.new_from_kev("spage=20&epage=22&pages=unused&foo=bar")
assert_equal "20", get_spage(co.referent)
co = ContextObject.new_from_kev("pages=20+-+22&foo=bar")
assert_equal "20", get_spage(co.referent)
co = ContextObject.new_from_kev("pages=20&foo=bar")
assert_equal "20", get_spage(co.referent)
end
def test_get_epage
co = ContextObject.new_from_kev("spage=20&epage=22&pages=unused&foo=bar")
assert_equal "22", get_epage(co.referent)
co = ContextObject.new_from_kev("pages=20+-+22&foo=bar")
assert_equal "22", get_epage(co.referent)
co = ContextObject.new_from_kev("pages=20&foo=bar")
assert_equal "20", get_epage(co.referent)
end
def test_title_is_serial
# heuristics for guessing if a citation represents a Journal OR Article,
# even in the presence of bad metadata, although we should respect good metadata.
assert_is_serial true, "format=journal&genre=journal&issn=12345678&jtitle=Journal"
assert_is_serial false, "format=book&issn=12345678&btitle=Book"
assert_is_serial false, "genre=book&issn=12345678&title=Book"
assert_is_serial false, "genre=bookitem&issn=12345678&btitle=Book"
assert_is_serial true, "jtitle=Journal&atitle=Article"
assert_is_serial true, "title=Journal&issn=12345678"
assert_is_serial false, "genre=dissertation&title=Dissertation&issn=12345678"
end
# test title_is_serial? implementation, for use only there.
def assert_is_serial(true_or_false, citation_kev)
co = ContextObject.new_from_kev(citation_kev)
assert (!true_or_false == !title_is_serial?(co.referent)), "Expect title_is_serial('#{citation_kev}') to be #{true_or_false}"
end
end
regression test for raw_search_title #32
# Encoding: UTF-8
# Doesn't yet cover everything, but started it to cover new func we wrote at least
require 'test_helper'
class MetadataHelperTest < ActiveSupport::TestCase
include MetadataHelper
ContextObject = OpenURL::ContextObject
def test_get_search_title_i18n
co = ContextObject.new_from_kev("sid=google&auinit=R&aulast=Dunayevskaya&title=Filosofía.+y+revolución:+de+Hegel+a+Sartre+y+de+Marx+a+Mao")
assert_equal "filosofía y revolución", get_search_title(co.referent)
end
def test_raw_search_title_regression
co = ContextObject.new_from_kev("resolve?ctx_ver=Z39.88-2004&ctx_enc=info:ofi/enc:UTF-8&ctx_tim=2013-11-25T10%3A59%3A44IST&url_ver=Z39.88-2004&url_ctx_fmt=infofi/fmt:kev:mtx:ctx&rfr_id=info:sid/primo.exlibrisgroup.com:primo3-Article-sciversesciencedirect_elsevier&rft_val_fmt=info:ofi/fmt:kev:mtx:&rft.genre=article&rft.atitle=Supercritical water gasification of biomass: Thermodynamic constraints&rft.jtitle=Bioresource Technology&rft.btitle=&rft.aulast=Castello&rft.auinit=&rft.auinit1=&rft.auinitm=&rft.ausuffix=&rft.au=Castello%2C Daniele&rft.aucorp=&rft.date=2011&rft.volume=102&rft.issue=16&rft.part=&rft.quarter=&rft.ssn=&rft.spage=7574&rft.epage=7582&rft.pages=7574-7582&rft.artnum=&rft.issn=0960-8524&rft.eissn=&rft.isbn=&rft.sici=&rft.coden=&rft_id=info:doi/10.1016/j.biortech.2011.05.017&rft_dat=S0960-8524(11)00656-0&rft.eisbn=&rft_id=info:oai/")
assert_equal "Bioresource Technology", raw_search_title(co.referent)
end
def test_get_isbn
co = ContextObject.new_from_kev("isbn=079284937X")
assert_equal "079284937X", get_isbn(co.referent)
co = ContextObject.new_from_kev("rft.isbn=079284937X")
assert_equal "079284937X", get_isbn(co.referent)
co = ContextObject.new_from_kev("isbn=0-435-08441-0")
assert_equal "0435084410", get_isbn(co.referent)
co = ContextObject.new_from_kev("isbn=0435084410+%28pbk.%29")
assert_equal "0435084410", get_isbn(co.referent)
end
def test_get_month
co = ContextObject.new_from_kev("date=2012-9-01&foo=bar")
assert_equal "9", get_month(co.referent)
co = ContextObject.new_from_kev("date=2012-10-01&foo=bar")
assert_equal "10", get_month(co.referent)
co = ContextObject.new_from_kev("date=2012-10&foo=bar")
assert_equal "10", get_month(co.referent)
co = ContextObject.new_from_kev("date=2012-10-01&month=9")
assert_equal "10", get_month(co.referent)
# If no date, try non-standard month
co = ContextObject.new_from_kev("month=9&foo=bar")
assert_equal "9", get_month(co.referent)
end
def test_get_spage
co = ContextObject.new_from_kev("spage=20&epage=22&pages=unused&foo=bar")
assert_equal "20", get_spage(co.referent)
co = ContextObject.new_from_kev("pages=20+-+22&foo=bar")
assert_equal "20", get_spage(co.referent)
co = ContextObject.new_from_kev("pages=20&foo=bar")
assert_equal "20", get_spage(co.referent)
end
def test_get_epage
co = ContextObject.new_from_kev("spage=20&epage=22&pages=unused&foo=bar")
assert_equal "22", get_epage(co.referent)
co = ContextObject.new_from_kev("pages=20+-+22&foo=bar")
assert_equal "22", get_epage(co.referent)
co = ContextObject.new_from_kev("pages=20&foo=bar")
assert_equal "20", get_epage(co.referent)
end
def test_title_is_serial
# heuristics for guessing if a citation represents a Journal OR Article,
# even in the presence of bad metadata, although we should respect good metadata.
assert_is_serial true, "format=journal&genre=journal&issn=12345678&jtitle=Journal"
assert_is_serial false, "format=book&issn=12345678&btitle=Book"
assert_is_serial false, "genre=book&issn=12345678&title=Book"
assert_is_serial false, "genre=bookitem&issn=12345678&btitle=Book"
assert_is_serial true, "jtitle=Journal&atitle=Article"
assert_is_serial true, "title=Journal&issn=12345678"
assert_is_serial false, "genre=dissertation&title=Dissertation&issn=12345678"
end
# test title_is_serial? implementation, for use only there.
def assert_is_serial(true_or_false, citation_kev)
co = ContextObject.new_from_kev(citation_kev)
assert (!true_or_false == !title_is_serial?(co.referent)), "Expect title_is_serial('#{citation_kev}') to be #{true_or_false}"
end
end |
require 'dxruby'
require_relative '../lib/dxrubyws'
# オブジェクトブラウザを作る実験
class WS::WSObjectBrowser < WS::WSWindow
def initialize(tx, ty, width, height, caption, obj)
super(tx, ty, width, height, caption)
lbx1 = WS::WSListBox.new(10,10,100,100)
lbx2 = WS::WSListBox.new(10,10,100,100)
self.client.add_control(lbx1, :lbx1)
self.client.add_control(lbx2, :lbx2)
lbl1 = WS::WSLabel.new(0, 0, 100, 16, "SuperClass : ")
lbl1.fore_color = C_BLACK
self.client.add_control(lbl1, :lbl1)
lbl2 = WS::WSLabel.new(0, 0, 200, 16)
lbl2.fore_color = C_BLACK
self.client.add_control(lbl2, :lbl2)
layout(:vbox) do
layout(:hbox) do
self.height = lbl1.height
self.resizable_height = false
add lbl1, false
add lbl2, false
layout
end
layout(:hbox) do
add lbx1, true, true
add lbx2, true, true
end
end
obj.class.instance_methods(false).each do |s|
lbx1.items << s
end
obj.instance_variables.each do |s|
lbx2.items << s
end
end
end
$ary = []
$ary << WS::WSMenuItem.new("Browse it") do |obj|
tmp = WS::WSObjectBrowser.new(Input.mouse_pos_x, Input.mouse_pos_y, 400, 200, "ObjectBrowser : " + obj.parent.to_s, obj.parent)
tmp.client.lbl2.caption = obj.parent.class.superclass.to_s
WS.desktop.add_control(tmp)
end
module UseObjectBrowser
def initialize(*args)
super
self.menuitems = $ary
end
end
class WS::WSWindow::WSWindowClient
include UseObjectBrowser
include WS::PopupMenu
end
# TestWindow1
w = WS::WSWindow.new(100, 100, 300, 100, "Test")
b = WS::WSButton.new(10, 10, 100, 20)
l = WS::WSLabel.new(10, 50, 100, 20)
w.client.add_control(b)
w.client.add_control(l)
image1 = Image.new(30, 30, C_WHITE)
image2 = Image.new(30, 30, C_BLACK)
image3 = Image.new(30, 30, C_RED)
image4 = Image.new(30, 30, C_BLUE)
i = WS::WSImage.new(200, 30, 30, 30)
i.extend WS::RightClickable
i.image = image1
i.add_handler(:mouse_over){|obj|obj.image = image2}
i.add_handler(:mouse_out){|obj|obj.image = image1}
i.add_handler(:click){|obj|obj.image = image3}
i.add_handler(:rightclick){|obj|obj.image = image4}
w.client.add_control(i)
WS.desktop.add_control(w)
# ListBoxTestWindow
w = WS::WSWindow.new(400, 100, 200, 250, "ListBoxTest")
lbx = WS::WSListBox.new(50, 30, 100, 160)
lbx.items.concat(String.instance_methods(false))
w.client.add_control(lbx)
lbl = WS::WSLabel.new(0, 0, 100, 16)
lbl.caption = lbx.items[lbx.cursor].to_s
lbx.add_handler(:select){|obj, cursor| lbl.caption = obj.items[cursor].to_s}
w.client.add_control(lbl)
w.layout(:vbox) do
add lbl, true
add lbx, true, true
end
WS::desktop.add_control(w)
# LayoutTestWindow
class Test < WS::WSWindow
def initialize
super(100, 300, 300, 100, "LayoutTest")
b1 = WS::WSButton.new(0, 0, 100, 20, "btn1")
b2 = WS::WSButton.new(0, 0, 100, 20, "btn2")
self.client.add_control(b1)
self.client.add_control(b2)
img = WS::WSImage.new(0, 0, 100, 10)
self.client.add_control(img)
img.add_handler(:resize) do
img.image.dispose if img.image
img.image = Image.new(img.width, img.height, C_WHITE).circle_fill(img.width/2, img.height/2, img.width>img.height ? img.height/2 : img.width/2, C_GREEN)
end
# オートレイアウトのテスト
# WSContainer#layoutでレイアウト定義を開始する。
# 内部でLayoutオブジェクトを作成し、そのインスタンスでブロックがinstance_evalされる。
# addメソッドはそのレイアウトボックス内にコントロールを追加する。
# layoutの引数は:hboxと:vboxで、それぞれ水平配置、垂直配置となり、コントロールを並べてくれる。
# WSContainer#layoutはコンテナ直下にレイアウトボックスを1つ作成する。
# Layout#layoutはその位置に可変サイズのレイアウトボックスを作成する。
# WSControl#resizable_width/resizable_heightがfalseのコントロールはサイズが変更されない。デフォルトはfalse。
# trueになってるやつは下記ルールでサイズが変更される。
# レイアウトボックス内にサイズ可変のものが無い場合:コントロールは均等の間隔で配置される。
# ある場合:レイアウトボックスがすべて埋まるように、可変サイズのオブジェクトを大きくする。
# このとき、可変サイズのオブジェクトが複数あったらそれらすべてが同じサイズになるように調整される。
# hbox(水平配置)のレイアウトボックス内にresizeble_height=trueのオブジェクトが存在した場合、
# 縦サイズはレイアウトボックスのサイズまで拡大される。縦横逆の場合も同じ。
# レイアウトボックスは縦横可変サイズのオブジェクトとして扱われ、
# 引数なしのlayoutだけを配置すると空っぽの可変サイズオブジェクトとして動作する。
# self.margin_top=/left=/bottom=/right=でレイアウトボックスのマージンを設定できる。
# self.をつけないとローカル変数への代入とみなされてしまうらしい。
# addメソッドの第2、第3引数でそれぞれresizable_width/resizable_heightを指定できるようにした。
layout(:vbox) do
self.margin_top = 10
self.margin_bottom = 10
layout(:hbox) do
add b1, false, true
add img, false, true
end
layout(:hbox) do
self.margin_left = 10
self.margin_right = 10
self.margin_top = 10
add b2, true, true
end
layout
end
end
end
t = Test.new
WS.desktop.add_control(t)
# とりあえずの右クリックメニューテスト
# 仕様はこれから考える。
ary = []
ary << WS::WSMenuItem.new("Add new Window") do
WS.desktop.add_control(WS::WSWindow.new(Input.mouse_pos_x, Input.mouse_pos_y, 300, 100, "PopupTestWindow"))
end
ary << nil # nilが入っていたらセパレータラインが表示される
ary << WS::WSMenuItem.new("Exit") do
break
end
# extendでいつでもポップアップ機能を追加できる。menuitemsにWSMenuItemの配列をセットする。
WS.desktop.extend WS::PopupMenu
WS.desktop.menuitems = ary
Window.loop do
WS.update
break if Input.key_push?(K_ESCAPE)
end
ウィンドウが狭くなってきたので拡大
require 'dxruby'
require_relative '../lib/dxrubyws'
Window.width, Window.height = 800, 600
# オブジェクトブラウザを作る実験
class WS::WSObjectBrowser < WS::WSWindow
def initialize(tx, ty, width, height, caption, obj)
super(tx, ty, width, height, caption)
lbx1 = WS::WSListBox.new(10,10,100,100)
lbx2 = WS::WSListBox.new(10,10,100,100)
self.client.add_control(lbx1, :lbx1)
self.client.add_control(lbx2, :lbx2)
lbl1 = WS::WSLabel.new(0, 0, 100, 16, "SuperClass : ")
lbl1.fore_color = C_BLACK
self.client.add_control(lbl1, :lbl1)
lbl2 = WS::WSLabel.new(0, 0, 200, 16)
lbl2.fore_color = C_BLACK
self.client.add_control(lbl2, :lbl2)
layout(:vbox) do
layout(:hbox) do
self.height = lbl1.height
self.resizable_height = false
add lbl1, false
add lbl2, false
layout
end
layout(:hbox) do
add lbx1, true, true
add lbx2, true, true
end
end
obj.class.instance_methods(false).each do |s|
lbx1.items << s
end
obj.instance_variables.each do |s|
lbx2.items << s
end
end
end
$ary = []
$ary << WS::WSMenuItem.new("Browse it") do |obj|
tmp = WS::WSObjectBrowser.new(Input.mouse_pos_x, Input.mouse_pos_y, 400, 200, "ObjectBrowser : " + obj.parent.to_s, obj.parent)
tmp.client.lbl2.caption = obj.parent.class.superclass.to_s
WS.desktop.add_control(tmp)
end
module UseObjectBrowser
def initialize(*args)
super
self.menuitems = $ary
end
end
class WS::WSWindow::WSWindowClient
include UseObjectBrowser
include WS::PopupMenu
end
# TestWindow1
w = WS::WSWindow.new(100, 100, 300, 100, "Test")
b = WS::WSButton.new(10, 10, 100, 20)
l = WS::WSLabel.new(10, 50, 100, 20)
w.client.add_control(b)
w.client.add_control(l)
image1 = Image.new(30, 30, C_WHITE)
image2 = Image.new(30, 30, C_BLACK)
image3 = Image.new(30, 30, C_RED)
image4 = Image.new(30, 30, C_BLUE)
i = WS::WSImage.new(200, 30, 30, 30)
i.extend WS::RightClickable
i.image = image1
i.add_handler(:mouse_over){|obj|obj.image = image2}
i.add_handler(:mouse_out){|obj|obj.image = image1}
i.add_handler(:click){|obj|obj.image = image3}
i.add_handler(:rightclick){|obj|obj.image = image4}
w.client.add_control(i)
WS.desktop.add_control(w)
# ListBoxTestWindow
w = WS::WSWindow.new(400, 100, 200, 250, "ListBoxTest")
lbx = WS::WSListBox.new(50, 30, 100, 160)
lbx.items.concat(String.instance_methods(false))
w.client.add_control(lbx)
lbl = WS::WSLabel.new(0, 0, 100, 16)
lbl.caption = lbx.items[lbx.cursor].to_s
lbx.add_handler(:select){|obj, cursor| lbl.caption = obj.items[cursor].to_s}
w.client.add_control(lbl)
w.layout(:vbox) do
add lbl, true
add lbx, true, true
end
WS::desktop.add_control(w)
# LayoutTestWindow
class Test < WS::WSWindow
def initialize
super(100, 300, 300, 100, "LayoutTest")
b1 = WS::WSButton.new(0, 0, 100, 20, "btn1")
b2 = WS::WSButton.new(0, 0, 100, 20, "btn2")
self.client.add_control(b1)
self.client.add_control(b2)
img = WS::WSImage.new(0, 0, 100, 10)
self.client.add_control(img)
img.add_handler(:resize) do
img.image.dispose if img.image
img.image = Image.new(img.width, img.height, C_WHITE).circle_fill(img.width/2, img.height/2, img.width>img.height ? img.height/2 : img.width/2, C_GREEN)
end
# オートレイアウトのテスト
# WSContainer#layoutでレイアウト定義を開始する。
# 内部でLayoutオブジェクトを作成し、そのインスタンスでブロックがinstance_evalされる。
# addメソッドはそのレイアウトボックス内にコントロールを追加する。
# layoutの引数は:hboxと:vboxで、それぞれ水平配置、垂直配置となり、コントロールを並べてくれる。
# WSContainer#layoutはコンテナ直下にレイアウトボックスを1つ作成する。
# Layout#layoutはその位置に可変サイズのレイアウトボックスを作成する。
# WSControl#resizable_width/resizable_heightがfalseのコントロールはサイズが変更されない。デフォルトはfalse。
# trueになってるやつは下記ルールでサイズが変更される。
# レイアウトボックス内にサイズ可変のものが無い場合:コントロールは均等の間隔で配置される。
# ある場合:レイアウトボックスがすべて埋まるように、可変サイズのオブジェクトを大きくする。
# このとき、可変サイズのオブジェクトが複数あったらそれらすべてが同じサイズになるように調整される。
# hbox(水平配置)のレイアウトボックス内にresizeble_height=trueのオブジェクトが存在した場合、
# 縦サイズはレイアウトボックスのサイズまで拡大される。縦横逆の場合も同じ。
# レイアウトボックスは縦横可変サイズのオブジェクトとして扱われ、
# 引数なしのlayoutだけを配置すると空っぽの可変サイズオブジェクトとして動作する。
# self.margin_top=/left=/bottom=/right=でレイアウトボックスのマージンを設定できる。
# self.をつけないとローカル変数への代入とみなされてしまうらしい。
# addメソッドの第2、第3引数でそれぞれresizable_width/resizable_heightを指定できるようにした。
layout(:vbox) do
self.margin_top = 10
self.margin_bottom = 10
layout(:hbox) do
add b1, false, true
add img, false, true
end
layout(:hbox) do
self.margin_left = 10
self.margin_right = 10
self.margin_top = 10
add b2, true, true
end
layout
end
end
end
t = Test.new
WS.desktop.add_control(t)
# とりあえずの右クリックメニューテスト
# 仕様はこれから考える。
ary = []
ary << WS::WSMenuItem.new("Add new Window") do
WS.desktop.add_control(WS::WSWindow.new(Input.mouse_pos_x, Input.mouse_pos_y, 300, 100, "PopupTestWindow"))
end
ary << nil # nilが入っていたらセパレータラインが表示される
ary << WS::WSMenuItem.new("Exit") do
break
end
# extendでいつでもポップアップ機能を追加できる。menuitemsにWSMenuItemの配列をセットする。
WS.desktop.extend WS::PopupMenu
WS.desktop.menuitems = ary
Window.loop do
WS.update
break if Input.key_push?(K_ESCAPE)
end
|
require 'bundler'
Bundler.setup
require 'rom/csv'
require 'ostruct'
csv_file = ARGV[0] || File.expand_path("./users.csv", File.dirname(__FILE__))
setup = ROM.setup(:csv, csv_file)
setup.relation(:users) do
def by_name(name)
restrict(name: name)
end
end
class User < OpenStruct
end
setup.mappers do
define(:users) do
register_as :entity
model User
end
end
rom = setup.finalize
user = rom.relation(:users).as(:entity).by_name('Jane').one
# => #<User id=2, name="Jane", email="jane@doe.org">
user or abort "user not found"
Fix example script
require 'bundler'
Bundler.setup
require 'rom/csv'
require 'ostruct'
csv_file = ARGV[0] || File.expand_path("./users.csv", File.dirname(__FILE__))
ROM.use :auto_registration
setup = ROM.setup(:csv, csv_file)
setup.relation(:users) do
def by_name(name)
restrict(name: name)
end
end
class User < OpenStruct
end
setup.mappers do
define(:users) do
register_as :entity
model User
end
end
rom = setup.finalize
user = rom.relation(:users).as(:entity).by_name('Jane').one
# => #<User id=2, name="Jane", email="jane@doe.org">
user or abort "user not found"
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'football_league/version'
Gem::Specification.new do |spec|
spec.name = "football_league"
spec.version = FootballLeague::VERSION
spec.authors = ["Haseeb Ahmad"]
spec.email = ["haseeb.ahmad717@gmail.com"]
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com' to prevent pushes to rubygems.org, or delete to allow pushes to any server."
end
spec.summary = %q{FootballLeague.}
spec.description = %q{FootballLeague. }
spec.homepage = "https://github.com/Haseeb717/football_league.git"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.8"
spec.add_development_dependency "rake", "~> 10.0"
end
first commit
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'football_league/version'
Gem::Specification.new do |spec|
spec.name = "football_league"
spec.version = FootballLeague::VERSION
spec.authors = ["Haseeb Ahmad"]
spec.email = ["haseeb.ahmad717@gmail.com"]
# if spec.respond_to?(:metadata)
# spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com' to prevent pushes to rubygems.org, or delete to allow pushes to any server."
# end
spec.summary = %q{FootballLeague.}
spec.description = %q{FootballLeague. }
spec.homepage = "https://github.com/Haseeb717/football_league.git"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.8"
spec.add_development_dependency "rake", "~> 10.0"
end
|
Adding langs seed
Language.create!(name: 'haskell',
test_runner_url: 'http://mumuki-hspec-server.herokuapp.com',
image_url: 'https://www.haskell.org/wikistatic/haskellwiki_logo.png')
Language.create!(name: 'gobstones',
test_runner_url: 'http://mumuki-gobstones-server.herokuapp.com',
image_url: 'https://avatars3.githubusercontent.com/u/8825549?v=3&s=30')
Language.create!(name: 'javascript',
test_runner_url: 'http://mumuki-mocha-server.herokuapp.com',
image_url: 'http://www.ninjajournal.com/wp-content/uploads/2014/03/javascript_logo_without_title.png')
Language.create!(name: 'c',
test_runner_url: 'http://162.243.111.176:8001',
image_url: 'https://www.haskell.org/wikistatic/haskellwiki_logo.png')
Language.create!(name: 'c++',
test_runner_url: 'http://162.243.111.176:8002',
image_url: 'https://www.haskell.org/wikistatic/haskellwiki_logo.png')
Language.create!(name: 'prolog',
test_runner_url: 'http://mumuki-plunit-server.herokuapp.com',
image_url: '"http://cdn.portableapps.com/SWI-PrologPortable_128.png')
Language.create!(name: 'ruby',
test_runner_url: 'http://162.243.111.176:8000',
image_url: 'http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Ruby_logo.svg/1000px-Ruby_logo.svg.png')
Language.create!(name: 'java',
test_runner_url: 'http://162.243.111.176:8003',
image_url: 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/a4/Java_logo_and_wordmark.svg/2000px-Java_logo_and_wordmark.svg.png')
Language.create!(name: 'wollok',
test_runner_url: 'http://mumuki-wollok-server.herokuapp.com',
image_url: 'https://raw.githubusercontent.com/uqbar-project/wollok/master/org.uqbar.project.wollok.ui/icons/wollok-logo-64.fw.png')
|
require './lib/expense'
require 'pry'
require 'PG'
@current_expense = nil
def welcome
puts "Alan please add content.\n\n"
main_menu
end
def main_menu
choice = nil
until choice == 'X'
puts "\n\nPlease choose an option, deary. "
puts "Press [A] to add an expense."
puts "Press [X] to exit."
choice = gets.chomp
case choice
when 'A'
add_expense
when 'X'
exit
else
puts "That's not an option, silly!\n\n"
end
end
end
def add_expense
puts "What did you buy?"
description = gets.chomp
puts "How much was it?"
price = gets.chomp.to_f
puts "What day was it? \nEnter date with mm/dd/yyyy. \nFor example: '01/08/1999'"
date = gets.chomp
@current_expense = Expense.new({'description' => description, 'amount' => price, 'date' => date})
binding.pry
puts "You have just saved: "
print_expense
end
def print_expense
puts "\n#{@current_expense.description}"
puts "Purchased on: #{@current_expense.date}"
puts "$#{@current_expense.amount}"
end
welcome
Add rest of main menu to ui and add methods for creating categories and listing all expenses and categories.
require './lib/expense'
require './lib/category'
require 'pry'
require 'PG'
DB = PG.connect({:dbname => 'expense_tracker'})
@current_expense = nil
@current_category = nil
def welcome
puts "Alan please add content.\n\n"
main_menu
end
def main_menu
choice = nil
until choice == 'X'
puts "\n\nPlease choose an option, deary. "
puts "Press [AE] to add an expense."
puts "Press [AC] to add a category."
puts "Press [EE] to edit an expense."
puts "Press [EC] to edit a category."
puts "Press [LE] to list all expenses."
puts "Press [LC] to list all categories."
puts "Press [CE] to place an expense into a category."
puts "Press [LEC] to list all expenses from one category."
puts "Press [LCE] to list all categories of one expense."
puts "Press [X] to exit."
choice = gets.chomp.upcase
case choice
when 'AE'
add_expense
when 'AC'
add_category
when 'EE'
edit_expense
when 'EC'
edit_category
when 'LE'
list_expenses
when 'LC'
list_categories
when 'LEC'
list_expenses_in_a_category
when 'LCE'
list_categories_in_a_expense
when 'X'
exit
else
puts "That's not an option, silly!\n\n"
end
end
end
def add_expense
puts "What did you buy?"
description = gets.chomp
puts "How much was it?"
price = gets.chomp.to_f
puts "What day was it? \nEnter date with mm/dd/yyyy. \nFor example: '01/08/1999'"
date = gets.chomp
@current_expense = Expense.new({'description' => description, 'amount' => price, 'date' => date})
@current_expense.save
puts "You have just saved: "
print_expense
end
def add_category
puts "What are you going to call this category? Enter a description."
description = gets.chomp
@current_category = Category.new({'description' => description})
@current_category.save
list_categories
end
def print_expense
puts "\n#{@current_expense.description}"
puts "Purchased on: #{@current_expense.date}"
puts "$#{@current_expense.amount}"
end
def list_expenses
if Expense.all.length == 0
puts "You have not logged any expenses yet."
else
puts "\nHere are all your logged expenses.\n"
Expense.all.each do |expense|
@current_expense = expense
print_expense
end
end
end
def list_categories
if Category.all.length == 0
puts "You have not created any categories yet."
else
puts "Here are all the categories you have for your expenses."
Category.all.each do |category|
puts "\n#{category.description}"
end
end
end
welcome
|
require 'mkmf'
# Test polling
def iodine_test_polling_support
iodine_poll_test_kqueue = <<EOS
\#define _GNU_SOURCE
\#include <stdlib.h>
\#include <sys/event.h>
int main(void) {
int fd = kqueue();
}
EOS
iodine_poll_test_epoll = <<EOS
\#define _GNU_SOURCE
\#include <stdlib.h>
\#include <stdio.h>
\#include <sys/types.h>
\#include <sys/stat.h>
\#include <fcntl.h>
\#include <sys/epoll.h>
int main(void) {
int fd = epoll_create1(EPOLL_CLOEXEC);
}
EOS
iodine_poll_test_poll = <<EOS
\#define _GNU_SOURCE
\#include <stdlib.h>
\#include <poll.h>
int main(void) {
struct pollfd plist[18];
memset(plist, 0, sizeof(plist[0]) * 18);
poll(plist, 1, 1);
}
EOS
# Test for manual selection and then TRY_COMPILE with each polling engine
if ENV['FIO_POLL']
puts "skipping polling tests, enforcing manual selection of: poll"
$defs << "-DFIO_ENGINE_POLL"
elsif ENV['FIO_FORCE_POLL']
puts "skipping polling tests, enforcing manual selection of: poll"
$defs << "-DFIO_ENGINE_POLL"
elsif ENV['FIO_FORCE_EPOLL']
puts "skipping polling tests, enforcing manual selection of: epoll"
$defs << "-DFIO_ENGINE_EPOLL"
elsif ENV['FIO_FORCE_KQUEUE']
puts "* Skipping polling tests, enforcing manual selection of: kqueue"
$defs << "-DFIO_ENGINE_KQUEUE"
elsif try_compile(iodine_poll_test_epoll)
puts "detected `epoll`"
$defs << "-DFIO_ENGINE_EPOLL"
elsif try_compile(iodine_poll_test_kqueue)
puts "detected `kqueue`"
$defs << "-DFIO_ENGINE_KQUEUE"
elsif try_compile(iodine_poll_test_poll)
puts "detected `poll` - this is suboptimal fallback!"
$defs << "-DFIO_ENGINE_POLL"
else
puts "* WARNING: No supported polling engine! expecting compilation to fail."
end
end
iodine_test_polling_support()
# Test for OpenSSL version equal to 1.0.0 or greater.
unless ENV['NO_SSL'] || ENV['NO_TLS'] || ENV["DISABLE_SSL"]
OPENSSL_TEST_CODE = <<EOS
\#include <openssl/bio.h>
\#include <openssl/err.h>
\#include <openssl/ssl.h>
\#if OPENSSL_VERSION_NUMBER < 0x10100000L
\#error "OpenSSL version too small"
\#endif
int main(void) {
SSL_library_init();
SSL_CTX *ctx = SSL_CTX_new(TLS_method());
SSL *ssl = SSL_new(ctx);
BIO *bio = BIO_new_socket(3, 0);
BIO_up_ref(bio);
SSL_set0_rbio(ssl, bio);
SSL_set0_wbio(ssl, bio);
}
EOS
dir_config("openssl")
begin
require 'openssl'
rescue LoadError
else
if have_library('crypto') && have_library('ssl')
puts "detected OpenSSL library, testing for version and required functions."
if try_compile(OPENSSL_TEST_CODE)
$defs << "-DHAVE_OPENSSL"
puts "confirmed OpenSSL to be version 1.1.0 or above (#{OpenSSL::OPENSSL_LIBRARY_VERSION})...\n* compiling with HAVE_OPENSSL."
else
puts "FAILED: OpenSSL version not supported (#{OpenSSL::OPENSSL_LIBRARY_VERSION} is too old)."
end
end
end
end
create_makefile 'iodine/iodine'
exclude test for openssl on Windows, use FIO_ENGINE_WSAPOLL
require 'mkmf'
# Test polling
def iodine_test_polling_support
iodine_poll_test_kqueue = <<EOS
\#define _GNU_SOURCE
\#include <stdlib.h>
\#include <sys/event.h>
int main(void) {
int fd = kqueue();
}
EOS
iodine_poll_test_epoll = <<EOS
\#define _GNU_SOURCE
\#include <stdlib.h>
\#include <stdio.h>
\#include <sys/types.h>
\#include <sys/stat.h>
\#include <fcntl.h>
\#include <sys/epoll.h>
int main(void) {
int fd = epoll_create1(EPOLL_CLOEXEC);
}
EOS
iodine_poll_test_poll = <<EOS
\#define _GNU_SOURCE
\#include <stdlib.h>
\#include <poll.h>
int main(void) {
struct pollfd plist[18];
memset(plist, 0, sizeof(plist[0]) * 18);
poll(plist, 1, 1);
}
EOS
# Test for manual selection and then TRY_COMPILE with each polling engine
if Gem.win_platform?
puts "skipping polling tests, using WSAPOLL on Windows"
$defs << "-DFIO_ENGINE_WSAPOLL"
elsif ENV['FIO_POLL']
puts "skipping polling tests, enforcing manual selection of: poll"
$defs << "-DFIO_ENGINE_POLL"
elsif ENV['FIO_FORCE_POLL']
puts "skipping polling tests, enforcing manual selection of: poll"
$defs << "-DFIO_ENGINE_POLL"
elsif ENV['FIO_FORCE_EPOLL']
puts "skipping polling tests, enforcing manual selection of: epoll"
$defs << "-DFIO_ENGINE_EPOLL"
elsif ENV['FIO_FORCE_KQUEUE']
puts "* Skipping polling tests, enforcing manual selection of: kqueue"
$defs << "-DFIO_ENGINE_KQUEUE"
elsif try_compile(iodine_poll_test_epoll)
puts "detected `epoll`"
$defs << "-DFIO_ENGINE_EPOLL"
elsif try_compile(iodine_poll_test_kqueue)
puts "detected `kqueue`"
$defs << "-DFIO_ENGINE_KQUEUE"
elsif try_compile(iodine_poll_test_poll)
puts "detected `poll` - this is suboptimal fallback!"
$defs << "-DFIO_ENGINE_POLL"
else
puts "* WARNING: No supported polling engine! expecting compilation to fail."
end
end
iodine_test_polling_support()
unless Gem.win_platform?
# Test for OpenSSL version equal to 1.0.0 or greater.
unless ENV['NO_SSL'] || ENV['NO_TLS'] || ENV["DISABLE_SSL"]
OPENSSL_TEST_CODE = <<EOS
\#include <openssl/bio.h>
\#include <openssl/err.h>
\#include <openssl/ssl.h>
\#if OPENSSL_VERSION_NUMBER < 0x10100000L
\#error "OpenSSL version too small"
\#endif
int main(void) {
SSL_library_init();
SSL_CTX *ctx = SSL_CTX_new(TLS_method());
SSL *ssl = SSL_new(ctx);
BIO *bio = BIO_new_socket(3, 0);
BIO_up_ref(bio);
SSL_set0_rbio(ssl, bio);
SSL_set0_wbio(ssl, bio);
}
EOS
dir_config("openssl")
begin
require 'openssl'
rescue LoadError
else
if have_library('crypto') && have_library('ssl')
puts "detected OpenSSL library, testing for version and required functions."
if try_compile(OPENSSL_TEST_CODE)
$defs << "-DHAVE_OPENSSL"
puts "confirmed OpenSSL to be version 1.1.0 or above (#{OpenSSL::OPENSSL_LIBRARY_VERSION})...\n* compiling with HAVE_OPENSSL."
else
puts "FAILED: OpenSSL version not supported (#{OpenSSL::OPENSSL_LIBRARY_VERSION} is too old)."
end
end
end
end
end
create_makefile 'iodine/iodine'
|
Really rudimentary CLI.
|
Fix on 1.8.x
|
コメント追加、最大化処理をメソッド化
|
Update wistia.rb
|
require 'pdf-reader'
require 'json'
require 'date'
# CapitalOneStatement object, with data parsed from a PDF monthly statement.
#
# @!attribute start_date [r]
# @return [Date] the first day of the monthly statement
#
# @!attribute end_date [r]
# @return [Date] the final day of the monthly statement
#
# @!attribute previous_balance [r]
# @return [Float] the "Previous Balance" field listed in the statement
#
# @!attribute total_payments [r]
# @return [Float] the "Payments and Credits" field listed in the statement
#
# @!attribute total_fees [r]
# @return [Float] the "Fees and Interest Charged" field listed in the statement
#
# @!attribute total_transactions [r]
# @return [Float] the "Transactions" field listed in the statement
#
# @!attribute new_balance [r]
# @return [Float] the New Balance listed in the statement
#
# @!attribute payments [r]
# @return [Array<CapitalOneStatement::Transaction>] array of payment transactions
#
# @!attribute transactions [r]
# @return [Array<CapitalOneStatement::Transaction>] array of charge transactions
class CapitalOneStatement
DATE_REGEX = /(\w{3})\. (\d\d) - (\w{3})\. (\d\d), (\d{4})/
AMOUNT_REGEX = /\(?\$[\d,]+\.\d\d\)?/
AMOUNT_ONLY_REGEX = /^ *#{AMOUNT_REGEX.source} *$/
TRANSACTION_REGEX = /^ *(\d+) +(\d\d) ([A-Z][A-Z][A-Z]) (.+[^ ]) +(#{
AMOUNT_REGEX.source
}) *$/
attr_reader :start_date,
:end_date,
:previous_balance,
:total_payments,
:total_fees,
:total_transactions,
:new_balance,
:payments,
:transactions
def initialize(pdf_path)
@dec_from_prev_year = nil
@year = nil
@start_date = nil
@end_date = nil
@previous_balance = nil
@total_payments = nil
@total_fees = nil
@total_transactions = nil
@new_balance = nil
@payments = []
@transactions = []
parse_from_pdf pdf_path
sort_by_trx_num = lambda {|trx| trx[:id]}
@payments = @payments .sort_by &sort_by_trx_num
@transactions = @transactions.sort_by &sort_by_trx_num
check_total(
'payments',
@total_payments,
@payments.inject(0) {|sum, trx| sum -= trx[:amount]}
)
check_total(
'transactions',
@total_transactions,
@transactions.inject(0) {|sum, trx| sum += trx[:amount]}
)
end
def to_json(*args)
{
:start_date => @start_date,
:end_date => @end_date,
:previous_balance => @previous_balance,
:total_payments => @total_payments,
:total_fees => @total_fees,
:total_transactions => @total_transactions,
:new_balance => @new_balance,
:payments => @payments,
:transactions => @transactions
}.to_json(*args)
end
private
def parse_from_pdf(pdf_path)
PDF::Reader.new(pdf_path).pages.each_with_index do |page, page_num|
if @year.nil?
walker = Struct.new(:year, :offset, :start_date, :end_date) do
def show_text_with_positioning(strings)
if strings.any? {|str| str =~ DATE_REGEX}
self.offset = ($1.upcase == 'DEC' && $3.upcase == 'JAN') ? 1 : 0
self.year = $5.to_i
self.start_date = Date.parse('%s-%s-%s' % [year - offset, $1, $2])
self.end_date = Date.parse('%s-%s-%s' % [year, $3, $4])
end
end
end.new
page.walk walker
@dec_from_prev_year = walker.offset == 1
@year = walker.year
@start_date = walker.start_date
@end_date = walker.end_date
end
enum = page.text.split("\n").each
loop do
parse_pdf_line(page_num, enum.next, (enum.peek() rescue nil))
end
end
end
def parse_pdf_line(page_num, line, next_line)
if @previous_balance.nil?
amount_strs = line.scan AMOUNT_REGEX
if amount_strs.size == 5
@previous_balance,
@total_payments,
@total_fees,
@total_transactions,
@new_balance = amount_strs.map {|amount| parse_amount(amount)}
end
end
transactions, payments = [(0..78), (80..-1)].map do |index|
str = line .to_s[index].to_s
next_str = next_line.to_s[index].to_s
repair_transaction_line str, next_str
end.map do |str|
parse_transaction(str)
end.compact.partition do |trx|
trx[:amount] >= 0
end
@transactions += transactions
@payments += payments
end
def repair_transaction_line(line, next_line)
if next_line =~ AMOUNT_ONLY_REGEX && !(line =~ AMOUNT_REGEX)
line += " #{next_line.strip}"
else
line
end
end
def parse_transaction(line)
return nil unless line =~ TRANSACTION_REGEX &&
$4 != "CAPITAL ONE MEMBER FEE"
raise "Failed to determine billing cycle dates" if @year.nil?
year = ($3.upcase == 'DEC' && @dec_from_prev_year) ? @year - 1 : @year
date = Date.parse('%s-%s-%s' % [year, $3, $2])
Transaction.new($1.to_i, date, $4, $5, parse_amount($5))
end
def parse_amount(amount)
num = amount.gsub(/[^\d.]/, '').to_f
amount.start_with?(?() ? -num : num
end
def check_total(type, expected, actual)
return if actual.round(2) == expected.round(2)
raise "Calculated %s payments mismatch %.2f != %.2f" % [
type,
actual,
expected
]
end
# CapitalOneStatement::Transaction represents a single credit transaction
class CapitalOneStatement::Transaction < Struct.new(
:id,
:date,
:description,
:amount_str,
:amount
)
# @!attribute id
# @return [Fixnum] transaction id
#
# @!attribute date
# @return [Date] the date of the transaction
#
# @!attribute description
# @return [String] the description of the transaction
#
# @!attribute amount_str
# @return [String] the dollar amount string of the transaction
#
# @!attribute amount
# @return [Float] the dollar amount parsed into a Float, negative for payments
# @return [String] JSON representation of Transaction
def to_json(*args)
to_h.to_json(*args)
end
end
end
Add fees transactions to model
require 'pdf-reader'
require 'json'
require 'date'
# CapitalOneStatement object, with data parsed from a PDF monthly statement.
#
# @!attribute start_date [r]
# @return [Date] the first day of the monthly statement
#
# @!attribute end_date [r]
# @return [Date] the final day of the monthly statement
#
# @!attribute previous_balance [r]
# @return [Float] the "Previous Balance" field listed in the statement
#
# @!attribute total_payments [r]
# @return [Float] the "Payments and Credits" field listed in the statement
#
# @!attribute total_fees [r]
# @return [Float] the "Fees and Interest Charged" field listed in the statement
#
# @!attribute total_transactions [r]
# @return [Float] the "Transactions" field listed in the statement
#
# @!attribute new_balance [r]
# @return [Float] the New Balance listed in the statement
#
# @!attribute payments [r]
# @return [Array<CapitalOneStatement::Transaction>] array of payment transactions
#
# @!attribute transactions [r]
# @return [Array<CapitalOneStatement::Transaction>] array of charge transactions
#
# @!attribute fees [r]
# @return [Array<CapitalOneStatement::Transaction>] array of fee transactions
class CapitalOneStatement
DATE_REGEX = /(\w{3})\. (\d\d) - (\w{3})\. (\d\d), (\d{4})/
AMOUNT_REGEX = /\(?\$[\d,]+\.\d\d\)?/
AMOUNT_ONLY_REGEX = /^ *#{AMOUNT_REGEX.source} *$/
FEES_REGEX = /Total Fees This Period +(#{AMOUNT_REGEX.source})/
INTEREST_REGEX = /Total Interest This Period +(#{AMOUNT_REGEX.source})/
TRANSACTION_REGEX = /^ *(\d+) +(\d\d) ([A-Z][A-Z][A-Z]) (.+[^ ]) +(#{
AMOUNT_REGEX.source
}) *$/
attr_reader :start_date,
:end_date,
:previous_balance,
:total_payments,
:total_fees,
:total_transactions,
:new_balance,
:payments,
:transactions
def initialize(pdf_path)
@dec_from_prev_year = nil
@year = nil
@start_date = nil
@end_date = nil
@previous_balance = nil
@new_balance = nil
@total_payments = nil
@total_transactions = nil
@total_fees = nil
@payments = []
@transactions = []
@fees = []
parse_from_pdf pdf_path
%w{payments transactions fees}.each do |type|
trxs = "@#{type}"
total = "@total_#{type}"
instance_variable_set(trxs, instance_variable_get(trxs).sort_by {|trx| trx[:id]})
check_total(
type,
instance_variable_get(total),
instance_variable_get(trxs).inject(0) {|sum, trx| sum += trx[:amount]}
)
end
end
def to_json(*args)
{
:start_date => @start_date,
:end_date => @end_date,
:previous_balance => @previous_balance,
:total_payments => @total_payments,
:total_fees => @total_fees,
:total_transactions => @total_transactions,
:new_balance => @new_balance,
:payments => @payments,
:transactions => @transactions,
:fees => @fees
}.to_json(*args)
end
private
def parse_from_pdf(pdf_path)
PDF::Reader.new(pdf_path).pages.each_with_index do |page, page_num|
if @year.nil?
walker = Struct.new(:year, :offset, :start_date, :end_date) do
def show_text_with_positioning(strings)
if strings.any? {|str| str =~ DATE_REGEX}
self.offset = ($1.upcase == 'DEC' && $3.upcase == 'JAN') ? 1 : 0
self.year = $5.to_i
self.start_date = Date.parse('%s-%s-%s' % [year - offset, $1, $2])
self.end_date = Date.parse('%s-%s-%s' % [year, $3, $4])
end
end
end.new
page.walk walker
@dec_from_prev_year = walker.offset == 1
@year = walker.year
@start_date = walker.start_date
@end_date = walker.end_date
end
enum = page.text.split("\n").each
loop do
parse_pdf_line(page_num, enum.next, (enum.peek() rescue nil))
end
end
end
def parse_pdf_line(page_num, line, next_line)
if @previous_balance.nil?
amount_strs = line.scan AMOUNT_REGEX
if amount_strs.size == 5
@previous_balance,
@total_payments,
@total_fees,
@total_transactions,
@new_balance = amount_strs.map {|amount| parse_amount(amount)}
@total_payments = -@total_payments
end
end
if line =~ FEES_REGEX && $1 != '$0.00'
check_billing_cycle
@fees << Transaction.new(
@fees.size + 1,
@end_date, "CAPITAL ONE MEMBER FEE",
$1,
parse_amount($1)
)
end
if line =~ INTEREST_REGEX && $1 != '$0.00'
check_billing_cycle
@fees << Transaction.new(
@fees.size + 1,
@end_date, "INTEREST CHARGE:PURCHASES",
$1,
parse_amount($1)
)
end
transactions, payments = [(0..78), (80..-1)].map do |index|
str = line .to_s[index].to_s
next_str = next_line.to_s[index].to_s
repair_transaction_line str, next_str
end.map do |str|
parse_transaction(str)
end.compact.partition do |trx|
trx[:amount] >= 0
end
@transactions += transactions
@payments += payments
end
def repair_transaction_line(line, next_line)
if next_line =~ AMOUNT_ONLY_REGEX && !(line =~ AMOUNT_REGEX)
line += " #{next_line.strip}"
else
line
end
end
def parse_transaction(line)
return nil unless line =~ TRANSACTION_REGEX &&
$4 != "CAPITAL ONE MEMBER FEE"
check_billing_cycle
year = ($3.upcase == 'DEC' && @dec_from_prev_year) ? @year - 1 : @year
date = Date.parse('%s-%s-%s' % [year, $3, $2])
Transaction.new($1.to_i, date, $4, $5, parse_amount($5))
end
def parse_amount(amount)
num = amount.gsub(/[^\d.]/, '').to_f
amount.start_with?(?() ? -num : num
end
def check_billing_cycle
raise "Failed to determine billing cycle dates" if @year.nil?
end
def check_total(type, expected, actual)
return if actual.round(2) == expected.round(2)
raise "Calculated %s payments mismatch %.2f != %.2f" % [
type,
actual,
expected
]
end
# CapitalOneStatement::Transaction represents a single credit transaction
class CapitalOneStatement::Transaction < Struct.new(
:id,
:date,
:description,
:amount_str,
:amount
)
# @!attribute id
# @return [Fixnum] transaction id
#
# @!attribute date
# @return [Date] the date of the transaction
#
# @!attribute description
# @return [String] the description of the transaction
#
# @!attribute amount_str
# @return [String] the dollar amount string of the transaction
#
# @!attribute amount
# @return [Float] the dollar amount parsed into a Float, negative for payments
# @return [String] JSON representation of Transaction
def to_json(*args)
to_h.to_json(*args)
end
end
end
|
module AfterParty
class TaskRecord < ActiveRecord::Base
def self.completed_task?(version)
all.any?{|t| t.version == version}
end
end
end
Add conditional attr_accessible
module AfterParty
class TaskRecord < ActiveRecord::Base
if ::Rails::VERSION::MAJOR.to_i == 3
attr_accessible :version
end
def self.completed_task?(version)
all.any?{|t| t.version == version}
end
end
end
|
class MiqExpression
attr_accessor :exp, :context_type, :preprocess_options
@@proto = VMDB::Config.new("vmdb").config[:product][:proto]
@@base_tables = %w{
AuditEvent
AvailabilityZone
BottleneckEvent
Chargeback
CloudResourceQuota
CloudTenant
Compliance
EmsCluster
EmsClusterPerformance
EmsEvent
ExtManagementSystem
Flavor
Host
HostPerformance
MiqGroup
MiqRegion
MiqRequest
MiqServer
MiqTemplate
MiqWorker
OntapFileShare
OntapLogicalDisk
OntapStorageSystem
OntapStorageVolume
OntapVolumeMetricsRollup
PolicyEvent
Repository
ResourcePool
SecurityGroup
Service
ServiceTemplate
Storage
StorageFile
StoragePerformance
TemplateCloud
TemplateInfra
User
VimPerformanceTrend
Vm
VmCloud
VmInfra
VmPerformance
Zone
}
if VdiFarm.is_available?
@@base_tables += %w{
VdiController
VdiDesktop
VdiDesktopPool
VdiEndpointDevice
VdiFarm
VdiSession
VdiUser
VmVdi
}
end
@@include_tables = %w{
advanced_settings
audit_events
availability_zones
cloud_resource_quotas
cloud_tenants
compliances
compliance_details
disks
ems_events
ems_clusters
ems_custom_attributes
evm_owners
event_logs
ext_management_systems
filesystem_drivers
filesystems
firewall_rules
flavors
groups
guest_applications
hardwares
hosts
host_services
kernel_drivers
lans
last_compliances
linux_initprocesses
miq_actions
miq_approval_stamps
miq_custom_attributes
miq_policy_sets
miq_provisions
miq_regions
miq_requests
miq_scsi_luns
miq_servers
miq_workers
ontap_concrete_extents
ontap_file_shares
ontap_logical_disks
ontap_plex_extents
ontap_raid_group_extents
ontap_storage_systems
ontap_storage_volumes
partitions
ports
processes
miq_provision_templates
miq_provision_vms
miq_templates
networks
nics
operating_systems
patches
registry_items
repositories
resource_pools
security_groups
service_templates
services
snapshots
storages
storage_adapters
storage_files
switches
users
vms
volumes
win32_services
zones
storage_systems
file_systems
hosted_file_shares
file_shares
logical_disks
storage_volumes
base_storage_extents
top_storage_extents
}
if VdiFarm.is_available?
@@include_tables += %w{
vdi_controllers
vdi_desktop_pools
vdi_desktops
vdi_endpoint_devices
vdi_farms
vdi_sessions
vdi_users
}
@@include_tables += %w{ldaps} if VdiFarm::MGMT_ENABLED == true
end
EXCLUDE_COLUMNS = %w{
^.*_id$
^blackbox_.*$
^id$
^min_derived_storage.*$
^max_derived_storage.*$
assoc_ids
capture_interval
filters
icon
intervals_in_rollup
max_cpu_ready_delta_summation
max_cpu_system_delta_summation
max_cpu_used_delta_summation
max_cpu_wait_delta_summation
max_derived_cpu_available
max_derived_cpu_reserved
max_derived_memory_available
max_derived_memory_reserved
memory_usage
min_cpu_ready_delta_summation
min_cpu_system_delta_summation
min_cpu_used_delta_summation
min_cpu_wait_delta_summation
min_derived_memory_available
min_derived_memory_reserved
min_derived_cpu_available
min_derived_cpu_reserved
min_max
options
password
policy_settings
^reserved$
resource_id
settings
tag_names
v_qualified_desc
disk_io_cost
disk_io_metric
net_io_cost
net_io_metric
fixed_2_cost
}
EXCLUDE_EXCEPTIONS = %w{
capacity_profile_1_memory_per_vm_with_min_max
capacity_profile_1_vcpu_per_vm_with_min_max
capacity_profile_2_memory_per_vm_with_min_max
capacity_profile_2_vcpu_per_vm_with_min_max
chain_id
guid
}
TAG_CLASSES = [
"EmsCloud", "ext_management_system",
"EmsCluster", "ems_cluster",
"EmsInfra", "ext_management_system",
"Host", "host",
"MiqGroup", "miq_group",
"MiqTemplate", "miq_template",
"Repository", "repository",
"ResourcePool", "resource_pool",
"Service", "service",
"Storage", "storage",
"TemplateCloud", "miq_template",
"TemplateInfra", "miq_template",
"User", "user",
"Vm", "vm",
"VmCloud", "vm",
"VmInfra", "vm"
]
FORMAT_SUB_TYPES = {
:boolean => {
:short_name => "Boolean",
:title => "Enter true or false"
},
:bytes => {
:short_name => "Bytes",
:title => "Enter the number of Bytes",
:units => [
["Bytes", :bytes],
["KB", :kilobytes],
["MB", :megabytes],
["GB", :gigabytes],
["TB", :terabytes]
]
},
:date => {
:short_name => "Date",
:title => "Click to Choose a Date"
},
:datetime => {
:short_name => "Date / Time",
:title => "Click to Choose a Date / Time"
},
:float => {
:short_name => "Number",
:title => "Enter a Number (like 12.56)"
},
:gigabytes => {
:short_name => "Gigabytes",
:title => "Enter the number of Gigabytes"
},
:integer => {
:short_name => "Integer",
:title => "Enter an Integer"
},
:kbps => {
:short_name => "KBps",
:title => "Enter the Kilobytes per second"
},
:kilobytes => {
:short_name => "Kilobytes",
:title => "Enter the number of Kilobytes"
},
:megabytes => {
:short_name => "Megabytes",
:title => "Enter the number of Megabytes"
},
:mhz => {
:short_name => "Mhz",
:title => "Enter the number of Megahertz"
},
:numeric_set => {
:short_name => "Number List",
:title => "Enter a list of numbers separated by commas"
},
:percent => {
:short_name => "Percent",
:title => "Enter a Percent (like 12.5)",
},
:regex => {
:short_name => "Regular Expression",
:title => "Enter a Regular Expression"
},
:ruby => {
:short_name => "Ruby Script",
:title => "Enter one or more lines of Ruby Script"
},
:string => {
:short_name => "Text String",
:title => "Enter a Text String"
},
:string_set => {
:short_name => "String List",
:title => "Enter a list of text strings separated by commas"
}
}
FORMAT_SUB_TYPES[:fixnum] = FORMAT_SUB_TYPES[:decimal] = FORMAT_SUB_TYPES[:integer]
FORMAT_SUB_TYPES[:mhz_avg] = FORMAT_SUB_TYPES[:mhz]
FORMAT_SUB_TYPES[:text] = FORMAT_SUB_TYPES[:string]
FORMAT_BYTE_SUFFIXES = FORMAT_SUB_TYPES[:bytes][:units].inject({}) {|h, (v,k)| h[k] = v; h}
def initialize(exp, ctype = nil)
@exp = exp
@context_type = ctype
end
def self.to_human(exp)
if exp.is_a?(self)
exp.to_human
else
if exp.is_a?(Hash)
case exp["mode"]
when "tag_expr"
return exp["expr"]
when "tag"
tag = [exp["ns"], exp["tag"]].join("/")
if exp["include"] == "none"
return "Not Tagged With #{tag}"
else
return "Tagged With #{tag}"
end
when "script"
if exp["expr"] == "true"
return "Always True"
else
return exp["expr"]
end
else
return self.new(exp).to_human
end
else
return exp.inspect
end
end
end
def to_human
self.class._to_human(@exp)
end
def self._to_human(exp, options={})
return exp unless exp.is_a?(Hash) || exp.is_a?(Array)
keys = exp.keys
keys.delete(:token)
operator = keys.first
case operator.downcase
when "like", "not like", "starts with", "ends with", "includes", "includes any", "includes all", "includes only", "limited to", "regular expression", "regular expression matches", "regular expression does not match", "equal", "=", "<", ">", ">=", "<=", "!=", "before", "after"
operands = self.operands2humanvalue(exp[operator], options)
clause = operands.join(" #{self.normalize_operator(operator)} ")
when "and", "or"
clause = "( " + exp[operator].collect {|operand| self._to_human(operand)}.join(" #{self.normalize_operator(operator)} ") + " )"
when "not", "!"
clause = self.normalize_operator(operator) + " ( " + self._to_human(exp[operator]) + " )"
when "is null", "is not null", "is empty", "is not empty"
clause = self.operands2humanvalue(exp[operator], options).first + " " + operator
when "contains"
operands = self.operands2humanvalue(exp[operator], options)
clause = operands.join(" #{self.normalize_operator(operator)} ")
when "find"
# FIND Vm.users-name = 'Administrator' CHECKALL Vm.users-enabled = 1
check = nil
check = "checkall" if exp[operator].include?("checkall")
check = "checkany" if exp[operator].include?("checkany")
check = "checkcount" if exp[operator].include?("checkcount")
raise "expression malformed, must contain one of 'checkall', 'checkany', 'checkcount'" unless check
check =~ /^check(.*)$/; mode = $1.upcase
clause = "FIND" + " " + self._to_human(exp[operator]["search"]) + " CHECK " + mode + " " + self._to_human(exp[operator][check], :include_table => false).strip
when "key exists"
clause = "KEY EXISTS #{exp[operator]['regkey']}"
when "value exists"
clause = "VALUE EXISTS #{exp[operator]['regkey']} : #{exp[operator]['regval']}"
when "ruby"
operands = self.operands2humanvalue(exp[operator], options)
operands[1] = "<RUBY Expression>"
clause = operands.join(" #{self.normalize_operator(operator)} \n")
when "is"
operands = self.operands2humanvalue(exp[operator], options)
clause = "#{operands.first} #{operator} #{operands.last}"
when "between dates", "between times"
col_name = exp[operator]["field"]
col_type = self.get_col_type(col_name)
col_human, dumy = self.operands2humanvalue(exp[operator], options)
vals_human = exp[operator]["value"].collect {|v| self.quote_human(v, col_type)}
clause = "#{col_human} #{operator} #{vals_human.first} AND #{vals_human.last}"
when "from"
col_name = exp[operator]["field"]
col_type = self.get_col_type(col_name)
col_human, dumy = self.operands2humanvalue(exp[operator], options)
vals_human = exp[operator]["value"].collect {|v| self.quote_human(v, col_type)}
clause = "#{col_human} #{operator} #{vals_human.first} THROUGH #{vals_human.last}"
end
# puts "clause: #{clause}"
return clause
end
def to_ruby(tz=nil)
tz ||= "UTC"
@ruby ||= self.class._to_ruby(@exp.deep_clone, @context_type, tz)
return @ruby.dup
end
def self._to_ruby(exp, context_type, tz)
return exp unless exp.is_a?(Hash) || exp.is_a?(Array)
operator = exp.keys.first
case operator.downcase
when "equal", "=", "<", ">", ">=", "<=", "!=", "before", "after"
col_type = self.get_col_type(exp[operator]["field"]) if exp[operator]["field"]
return self._to_ruby({"date_time_with_logical_operator" => exp}, context_type, tz) if col_type == :date || col_type == :datetime
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = operands.join(" #{self.normalize_ruby_operator(operator)} ")
when "includes all"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = "(#{operands[0]} & #{operands[1]}) == #{operands[1]}"
when "includes any"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = "(#{operands[1]} - #{operands[0]}) != #{operands[1]}"
when "includes only", "limited to"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = "(#{operands[0]} - #{operands[1]}) == []"
when "like", "not like", "starts with", "ends with", "includes"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
case operator.downcase
when "starts with"
operands[1] = "/^" + self.re_escape(operands[1].to_s) + "/"
when "ends with"
operands[1] = "/" + self.re_escape(operands[1].to_s) + "$/"
else
operands[1] = "/" + self.re_escape(operands[1].to_s) + "/"
end
clause = operands.join(" #{self.normalize_ruby_operator(operator)} ")
clause = "!(" + clause + ")" if operator.downcase == "not like"
when "regular expression matches", "regular expression does not match"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
operands[1] = "/" + operands[1].to_s + "/" unless operands[1].starts_with?("/") && (operands[1].ends_with?("/") || operands[1][-2..-2] == "/")
clause = operands.join(" #{self.normalize_ruby_operator(operator)} ")
when "and", "or"
clause = "(" + exp[operator].collect {|operand| self._to_ruby(operand, context_type, tz)}.join(" #{self.normalize_ruby_operator(operator)} ") + ")"
when "not", "!"
clause = self.normalize_ruby_operator(operator) + "(" + self._to_ruby(exp[operator], context_type, tz) + ")"
when "is null", "is not null", "is empty", "is not empty"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = operands.join(" #{self.normalize_ruby_operator(operator)} ")
when "contains"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = operands.join(" #{self.normalize_operator(operator)} ")
when "find"
# FIND Vm.users-name = 'Administrator' CHECKALL Vm.users-enabled = 1
check = nil
check = "checkall" if exp[operator].include?("checkall")
check = "checkany" if exp[operator].include?("checkany")
if exp[operator].include?("checkcount")
check = "checkcount"
op = exp[operator][check].keys.first
exp[operator][check][op]["field"] = "<count>"
end
raise "expression malformed, must contain one of 'checkall', 'checkany', 'checkcount'" unless check
check =~ /^check(.*)$/; mode = $1.downcase
clause = "<find><search>" + self._to_ruby(exp[operator]["search"], context_type, tz) + "</search><check mode=#{mode}>" + self._to_ruby(exp[operator][check], context_type, tz) + "</check></find>"
when "key exists"
clause = self.operands2rubyvalue(operator, exp[operator], context_type)
when "value exists"
clause = self.operands2rubyvalue(operator, exp[operator], context_type)
when "ruby"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
col_type = self.get_col_type(exp[operator]["field"]) || "string"
clause = "__start_ruby__ __start_context__#{operands[0]}__type__#{col_type}__end_context__ __start_script__#{operands[1]}__end_script__ __end_ruby__"
when "is"
col_name = exp[operator]["field"]
col_ruby, dummy = self.operands2rubyvalue(operator, {"field" => col_name}, context_type)
col_type = self.get_col_type(col_name)
value = exp[operator]["value"]
if col_type == :date
if self.date_time_value_is_relative?(value)
start_val = self.quote(self.normalize_date_time(value, "UTC", "beginning").to_date, :date)
end_val = self.quote(self.normalize_date_time(value, "UTC", "end").to_date, :date)
clause = "val=#{col_ruby}; !val.nil? && val.to_date >= #{start_val} && val.to_date <= #{end_val}"
else
value = self.quote(self.normalize_date_time(value, "UTC", "beginning").to_date, :date)
clause = "val=#{col_ruby}; !val.nil? && val.to_date == #{value}"
end
else
start_val = self.quote(self.normalize_date_time(value, tz, "beginning").utc, :datetime)
end_val = self.quote(self.normalize_date_time(value, tz, "end").utc, :datetime)
clause = "val=#{col_ruby}; !val.nil? && val.to_time >= #{start_val} && val.to_time <= #{end_val}"
end
when "from"
col_name = exp[operator]["field"]
col_ruby, dummy = self.operands2rubyvalue(operator, {"field" => col_name}, context_type)
col_type = self.get_col_type(col_name)
start_val, end_val = exp[operator]["value"]
start_val = self.quote(self.normalize_date_time(start_val, tz, "beginning").utc, :datetime)
end_val = self.quote(self.normalize_date_time(end_val, tz, "end").utc, :datetime)
clause = "val=#{col_ruby}; !val.nil? && val.to_time >= #{start_val} && val.to_time <= #{end_val}"
when "date_time_with_logical_operator"
exp = exp[operator]
operator = exp.keys.first
col_name = exp[operator]["field"]
col_type = self.get_col_type(col_name)
col_ruby, dummy = self.operands2rubyvalue(operator, {"field" => col_name}, context_type)
normalized_operator = self.normalize_ruby_operator(operator)
mode = case normalized_operator
when ">", "<=" then "end" # (> <date> 23::59:59), (<= <date> 23::59:59)
when "<", ">=" then "beginning" # (< <date> 00::00:00), (>= <date> 00::00:00)
end
val = self.normalize_date_time(exp[operator]["value"], tz, mode)
clause = "val=#{col_ruby}; !val.nil? && val.to_time #{normalized_operator} #{self.quote(val.utc, :datetime)}"
else
raise "operator '#{operator}' is not supported"
end
# puts "clause: #{clause}"
return clause
end
def self.normalize_date_time(rel_time, tz, mode="beginning")
# time_spec =
# <value> <interval> Ago
# "Today"
# "Yesterday"
# "Now"
# "Last Week"
# "Last Month"
# "Last Quarter"
# "This Week"
# "This Month"
# "This Quarter"
rt = rel_time.downcase
if rt.starts_with?("this") || rt.starts_with?("last")
# Convert these into the time spec form: <value> <interval> Ago
value, interval = rt.split
rt = "#{value == "this" ? 0 : 1} #{interval} ago"
end
if rt.ends_with?("ago")
# Time spec <value> <interval> Ago
value, interval, ago = rt.split
interval = interval.pluralize
if interval == "hours"
self.beginning_or_end_of_hour(value.to_i.hours.ago.in_time_zone(tz), mode)
elsif interval == "quarters"
ts = Time.now.in_time_zone(tz).beginning_of_quarter
(ts - (value.to_i * 3.months)).send("#{mode}_of_quarter")
else
value.to_i.send(interval).ago.in_time_zone(tz).send("#{mode}_of_#{interval.singularize}")
end
elsif rt == "today"
Time.now.in_time_zone(tz).send("#{mode}_of_day")
elsif rt == "yesterday"
1.day.ago.in_time_zone(tz).send("#{mode}_of_day")
elsif rt == "now"
self.beginning_or_end_of_hour(Time.now.in_time_zone(tz), mode)
else
# Assume it's an absolute date or time
value_is_date = !rel_time.include?(":")
ts = Time.use_zone(tz) { Time.zone.parse(rel_time) }
ts = ts.send("#{mode}_of_day") if mode && value_is_date
ts
end
end
def self.beginning_or_end_of_hour(ts, mode)
ts_str = ts.iso8601
ts_str[14..18] = mode == "end" ? "59:59" : "00:00"
Time.parse(ts_str)
end
def self.date_time_value_is_relative?(value)
v = value.downcase
v.starts_with?("this") || v.starts_with?("last") || v.ends_with?("ago") || ["today", "yesterday", "now"].include?(v)
end
def to_sql(tz=nil)
tz ||= "UTC"
@pexp, attrs = self.preprocess_for_sql(@exp.deep_clone)
sql = self._to_sql(@pexp, tz)
incl = self.includes_for_sql unless sql.blank?
return [sql, incl, attrs]
end
def _to_sql(exp, tz)
return exp unless exp.is_a?(Hash) || exp.is_a?(Array)
operator = exp.keys.first
return if operator.nil?
case operator.downcase
when "equal", "=", "<", ">", ">=", "<=", "!=", "before", "after"
col_type = self.class.get_col_type(exp[operator]["field"]) if exp[operator]["field"]
return self._to_sql({"date_time_with_logical_operator" => exp}, tz) if col_type == :date || col_type == :datetime
operands = self.class.operands2sqlvalue(operator, exp[operator])
clause = operands.join(" #{self.class.normalize_sql_operator(operator)} ")
when "like", "not like", "starts with", "ends with", "includes"
operands = self.class.operands2sqlvalue(operator, exp[operator])
case operator.downcase
when "starts with"
operands[1] = "'" + operands[1].to_s + "%'"
when "ends with"
operands[1] = "'%" + operands[1].to_s + "'"
when "like", "not like", "includes"
operands[1] = "'%" + operands[1].to_s + "%'"
end
clause = operands.join(" #{self.class.normalize_sql_operator(operator)} ")
clause = "!(" + clause + ")" if operator.downcase == "not like"
when "and", "or"
operands = exp[operator].collect {|operand|
o = self._to_sql(operand, tz)
o.blank? ? nil : o
}.compact
if operands.length > 1
clause = "(" + operands.join(" #{self.class.normalize_sql_operator(operator)} ") + ")"
elsif operands.length == 1 # Operands may have been stripped out during pre-processing
clause = "(" + operands.first + ")"
else # All operands may have been stripped out during pre-processing
clause = nil
end
when "not", "!"
clause = self.class.normalize_sql_operator(operator) + " " + self._to_sql(exp[operator], tz)
when "is null", "is not null"
operands = self.class.operands2sqlvalue(operator, exp[operator])
clause = "(#{operands[0]} #{self.class.normalize_sql_operator(operator)})"
when "is empty", "is not empty"
col = exp[operator]["field"]
col_type = self.col_details[col].nil? ? :string : self.col_details[col][:data_type]
operands = self.class.operands2sqlvalue(operator, exp[operator])
clause = "(#{operands[0]} #{operator.sub(/empty/i, "NULL")})"
if col_type == :string
conjunction = (operator.downcase == 'is empty') ? 'OR' : 'AND'
clause = "(#{clause} #{conjunction} (#{operands[0]} #{self.class.normalize_sql_operator(operator)} ''))"
end
when "contains"
# Only support for tags of the main model
if exp[operator].has_key?("tag")
klass, ns = exp[operator]["tag"].split(".")
ns = "/" + ns.split("-").join("/")
ns = ns.sub(/(\/user_tag\/)/, "/user/") # replace with correct namespace for user tags
tag = exp[operator]["value"]
klass = klass.constantize
ids = klass.find_tagged_with(:any => tag, :ns => ns).pluck(:id)
clause = "(#{klass.send(:sanitize_sql_for_conditions, :id => ids)})"
else
db, field = exp[operator]["field"].split(".")
model = db.constantize
assoc, field = field.split("-")
ref = model.reflections[assoc.to_sym]
inner_where = "#{field} = '#{exp[operator]["value"]}'"
if cond = ref.options.fetch(:conditions, nil) # Include ref.options[:conditions] in inner select if exists
cond = ref.options[:class_name].constantize.send(:sanitize_sql_for_assignment, cond)
inner_where = "(#{inner_where}) AND (#{cond})"
end
clause = "#{model.table_name}.id IN (SELECT DISTINCT #{ref.foreign_key} FROM #{ref.table_name} WHERE #{inner_where})"
end
when "is"
col_name = exp[operator]["field"]
col_sql, dummy = self.class.operands2sqlvalue(operator, {"field" => col_name})
col_type = self.class.get_col_type(col_name)
value = exp[operator]["value"]
if col_type == :date
if self.class.date_time_value_is_relative?(value)
start_val = self.class.quote(self.class.normalize_date_time(value, "UTC", "beginning").to_date, :date, :sql)
end_val = self.class.quote(self.class.normalize_date_time(value, "UTC", "end").to_date, :date, :sql)
clause = "#{col_sql} BETWEEN #{start_val} AND #{end_val}"
else
value = self.class.quote(self.class.normalize_date_time(value, "UTC", "beginning").to_date, :date, :sql)
clause = "#{col_sql} = #{value}"
end
else
start_val = self.class.quote(self.class.normalize_date_time(value, tz, "beginning").utc, :datetime, :sql)
end_val = self.class.quote(self.class.normalize_date_time(value, tz, "end").utc, :datetime, :sql)
clause = "#{col_sql} BETWEEN #{start_val} AND #{end_val}"
end
when "from"
col_name = exp[operator]["field"]
col_sql, dummy = self.class.operands2sqlvalue(operator, {"field" => col_name})
col_type = self.class.get_col_type(col_name)
start_val, end_val = exp[operator]["value"]
start_val = self.class.quote(self.class.normalize_date_time(start_val, tz, "beginning").utc, :datetime, :sql)
end_val = self.class.quote(self.class.normalize_date_time(end_val, tz, "end").utc, :datetime, :sql)
clause = "#{col_sql} BETWEEN #{start_val} AND #{end_val}"
when "date_time_with_logical_operator"
exp = exp[operator]
operator = exp.keys.first
col_name = exp[operator]["field"]
col_type = self.class.get_col_type(col_name)
col_sql, dummy = self.class.operands2sqlvalue(operator, {"field" => col_name})
normalized_operator = self.class.normalize_sql_operator(operator)
mode = case normalized_operator
when ">", "<=" then "end" # (> <date> 23::59:59), (<= <date> 23::59:59)
when "<", ">=" then "beginning" # (< <date> 00::00:00), (>= <date> 00::00:00)
end
val = self.class.normalize_date_time(exp[operator]["value"], tz, mode)
clause = "#{col_sql} #{normalized_operator} #{self.class.quote(val.utc, :datetime, :sql)}"
else
raise "operator '#{operator}' is not supported"
end
# puts "clause: #{clause}"
return clause
end
def preprocess_for_sql(exp, attrs=nil)
attrs ||= {:supported_by_sql => true}
operator = exp.keys.first
case operator.downcase
when "and"
exp[operator].dup.each { |atom| self.preprocess_for_sql(atom, attrs)}
exp[operator] = exp[operator].collect {|o| o.blank? ? nil : o}.compact # Clean out empty operands
exp.delete(operator) if exp[operator].empty?
when "or"
or_attrs = {:supported_by_sql => true}
exp[operator].each_with_index { |atom,i|
self.preprocess_for_sql(atom, or_attrs)
exp[operator][i] = nil if atom.blank?
}
exp[operator].compact!
attrs.merge!(or_attrs)
exp.delete(operator) if !or_attrs[:supported_by_sql] || exp[operator].empty? # Clean out unsupported or empty operands
when "not"
self.preprocess_for_sql(exp[operator], attrs)
exp.delete(operator) if exp[operator].empty? # Clean out empty operands
else
# check operands to see if they can be represented in sql
unless sql_supports_atom?(exp)
attrs[:supported_by_sql] = false
exp.delete(operator)
end
end
return exp.empty? ? [nil, attrs] : [exp, attrs]
end
def sql_supports_atom?(exp)
operator = exp.keys.first
case operator.downcase
when "contains"
if exp[operator].keys.include?("tag") && exp[operator]["tag"].split(".").length == 2 # Only support for tags of the main model
return true
elsif exp[operator].keys.include?("field") && exp[operator]["field"].split(".").length == 2
db, field = exp[operator]["field"].split(".")
assoc, field = field.split("-")
ref = db.constantize.reflections[assoc.to_sym]
return false unless ref
return false unless ref.macro == :has_many || ref.macro == :has_one
return false if ref.options && ref.options.has_key?(:as)
return field_in_sql?(exp[operator]["field"])
else
return false
end
when "includes"
# Support includes operator using "LIKE" only if first operand is in main table
if exp[operator].has_key?("field") && (!exp[operator]["field"].include?(".") || (exp[operator]["field"].include?(".") && exp[operator]["field"].split(".").length == 2))
return field_in_sql?(exp[operator]["field"])
else
# TODO: Support includes operator for sub-sub-tables
return false
end
when "find", "regular expression matches", "regular expression does not match", "key exists", "value exists", "ruby"
return false
else
# => false if operand is a tag
return false if exp[operator].keys.include?("tag")
# => TODO: support count of child relationship
return false if exp[operator].has_key?("count")
return field_in_sql?(exp[operator]["field"])
end
end
def field_in_sql?(field)
# => false if operand is from a virtual reflection
return false if self.field_from_virtual_reflection?(field)
# => false if operand if a virtual coulmn
return false if self.field_is_virtual_column?(field)
# => false if excluded by special case defined in preprocess options
return false if self.field_excluded_by_preprocess_options?(field)
return true
end
def field_from_virtual_reflection?(field)
self.col_details[field][:virtual_reflection]
end
def field_is_virtual_column?(field)
self.col_details[field][:virtual_column]
end
def field_excluded_by_preprocess_options?(field)
self.col_details[field][:excluded_by_preprocess_options]
end
def col_details
@col_details ||= self.class.get_cols_from_expression(@exp, @preprocess_options)
end
def includes_for_sql
result = {}
self.col_details.each_value do |v|
self.class.deep_merge_hash(result, v[:include])
end
return result
end
def columns_for_sql(exp=nil, result = nil)
exp ||= self.exp
result ||= []
return result unless exp.kind_of?(Hash)
operator = exp.keys.first
if exp[operator].kind_of?(Hash) && exp[operator].has_key?("field")
unless exp[operator]["field"] == "<count>" || self.field_from_virtual_reflection?(exp[operator]["field"]) || self.field_is_virtual_column?(exp[operator]["field"])
col = exp[operator]["field"]
if col.include?(".")
col = col.split(".").last
col = col.sub("-", ".")
else
col = col.split("-").last
end
result << col
end
else
exp[operator].dup.to_miq_a.each { |atom| self.columns_for_sql(atom, result) }
end
return result.compact.uniq
end
def self.deep_merge_hash(hash1,hash2)
return hash1 if hash2.nil?
hash2.each_key do |k1|
if hash1.key?(k1)
deep_merge_hash(hash1[k1],hash2[k1])
else
hash1[k1] = hash2[k1]
end
end
end
def self.merge_where_clauses_and_includes(where_clauses, includes)
[self.merge_where_clauses(*where_clauses), self.merge_includes(*includes)]
end
def self.merge_where_clauses(*list)
l = list.compact.collect do |s|
s = MiqReport.send(:sanitize_sql_for_conditions, s)
"(#{s})"
end
return l.empty? ? nil : l.join(" AND ")
end
def self.merge_includes(*incl_list)
return nil if incl_list.blank?
result = {}
incl_list.each do |i|
self.deep_merge_hash(result, i)
end
return result
end
def self.get_cols_from_expression(exp, options={})
result = {}
if exp.kind_of?(Hash)
if exp.has_key?("field")
result[exp["field"]] = self.get_col_info(exp["field"], options) unless exp["field"] == "<count>"
elsif exp.has_key?("count")
result[exp["count"]] = self.get_col_info(exp["count"], options)
elsif exp.has_key?("tag")
# ignore
else
exp.each_value { |v| result.merge!(self.get_cols_from_expression(v, options)) }
end
elsif exp.kind_of?(Array)
exp.each {|v| result.merge!(self.get_cols_from_expression(v, options)) }
end
return result
end
def self.get_col_info(field, options={})
result ||= {:data_type => nil, :virtual_reflection => false, :virtual_column => false, :excluded_by_preprocess_options => false, :tag => false, :include => {}}
col = field.split("-").last if field.include?("-")
parts = field.split("-").first.split(".")
model = parts.shift
if model.downcase == "managed" || parts.last == "managed"
result[:data_type] = :string
result[:tag] = true
return result
end
model = model_class(model)
cur_incl = result[:include]
parts.each do |assoc|
assoc = assoc.to_sym
ref = model.reflections_with_virtual[assoc]
result[:virtual_reflection] = true if ref.kind_of?(VirtualReflection)
unless result[:virtual_reflection]
cur_incl[assoc] ||= {}
cur_incl = cur_incl[assoc]
end
unless ref
result[:virtual_reflection] = true
result[:virtual_column] = true
return result
end
model = ref.klass
end
if col
result[:data_type] = self.col_type(model, col)
result[:format_sub_type] = MiqReport::FORMAT_DEFAULTS_AND_OVERRIDES[:sub_types_by_column][col.to_sym] || result[:data_type]
result[:virtual_column] = true if model.virtual_columns_hash.include?(col.to_s)
result[:excluded_by_preprocess_options] = self.exclude_col_by_preprocess_options?(col, options)
end
return result
end
def self.exclude_col_by_preprocess_options?(col, options)
return false unless options.kind_of?(Hash)
if options[:vim_performance_daily_adhoc]
return VimPerformanceDaily.excluded_cols_for_expressions.include?(col.to_sym)
end
return false
end
def self.evaluate(expression, obj, inputs={})
ruby_exp = expression.is_a?(Hash) ? self.new(expression).to_ruby : expression.to_ruby
$log.debug("MIQ(Expression-evaluate) Expression before substitution: #{ruby_exp}")
subst_expr = self.subst(ruby_exp, obj, inputs)
$log.debug("MIQ(Expression-evaluate) Expression after substitution: #{subst_expr}")
result = eval(subst_expr) ? true : false
$log.debug("MIQ(Expression-evaluate) Expression evaluation result: [#{result}]")
return result
end
def evaluate(obj, inputs={})
self.class.evaluate(self, obj, inputs)
end
def self.evaluate_atoms(exp, obj, inputs={})
exp = exp.is_a?(self) ? copy_hash(exp.exp) : exp
exp["result"] = self.evaluate(exp, obj, inputs)
operators = exp.keys
operators.each {|k|
if ["and", "or"].include?(k.to_s.downcase) # and/or atom is an array of atoms
exp[k].each {|atom|
self.evaluate_atoms(atom, obj, inputs)
}
elsif ["not", "!"].include?(k.to_s.downcase) # not atom is a hash expression
self.evaluate_atoms(exp[k], obj, inputs)
else
next
end
}
return exp
end
def self.subst(ruby_exp, obj, inputs)
Condition.subst(ruby_exp, obj, inputs)
end
def self.operands2humanvalue(ops, options={})
# puts "Enter: operands2humanvalue: ops: #{ops.inspect}"
ret = []
if ops["tag"]
v = nil
ret.push(ops["alias"] || self.value2human(ops["tag"], options))
MiqExpression.get_entry_details(ops["tag"]).each {|t|
v = "'" + t.first + "'" if t.last == ops["value"]
}
if ops["value"] == :user_input
v = "<user input>"
else
v ||= ops["value"].is_a?(String) ? "'" + ops["value"] + "'" : ops["value"]
end
ret.push(v)
elsif ops["field"]
ops["value"] ||= ''
if ops["field"] == "<count>"
ret.push(nil)
ret.push(ops["value"])
else
ret.push(ops["alias"] || self.value2human(ops["field"], options))
if ops["value"] == :user_input
ret.push("<user input>")
else
col_type = self.get_col_type(ops["field"]) || "string"
ret.push(self.quote_human(ops["value"], col_type.to_s))
end
end
elsif ops["count"]
ret.push("COUNT OF " + (ops["alias"] || self.value2human(ops["count"], options)).strip)
if ops["value"] == :user_input
ret.push("<user input>")
else
ret.push(ops["value"])
end
elsif ops["regkey"]
ops["value"] ||= ''
ret.push(ops["regkey"] + " : " + ops["regval"])
ret.push(ops["value"].is_a?(String) ? "'" + ops["value"] + "'" : ops["value"])
elsif ops["value"]
ret.push(nil)
ret.push(ops["value"])
end
return ret
end
def self.value2human(val, options={})
options = {
:include_model => true,
:include_table => true
}.merge(options)
@company ||= VMDB::Config.new("vmdb").config[:server][:company]
tables, col = val.split("-")
first = true
val_is_a_tag = false
ret = ""
if options[:include_table] == true
friendly = tables.split(".").collect {|t|
if t.downcase == "managed"
val_is_a_tag = true
@company + " Tags"
elsif t.downcase == "user_tag"
"My Tags"
else
if first
first = nil
next unless options[:include_model] == true
Dictionary.gettext(t, :type=>:model, :notfound=>:titleize)
else
Dictionary.gettext(t, :type=>:table, :notfound=>:titleize)
end
end
}.compact
ret = friendly.join(".")
ret << " : " unless ret.blank? || col.blank?
end
if val_is_a_tag
if col
classification = options[:classification] || Classification.find_by_name(col)
ret << (classification ? classification.description : col)
end
else
model = tables.blank? ? nil : tables.split(".").last.singularize.camelize
dict_col = model.nil? ? col : [model, col].join(".")
ret << Dictionary.gettext(dict_col, :type=>:column, :notfound=>:titleize) if col
end
ret = " #{ret}" unless ret.include?(":")
ret
end
def self.operands2sqlvalue(operator, ops)
# puts "Enter: operands2rubyvalue: operator: #{operator}, ops: #{ops.inspect}"
operator = operator.downcase
ret = []
if ops["field"]
ret << self.get_sqltable(ops["field"].split("-").first) + "." + ops["field"].split("-").last
col_type = self.get_col_type(ops["field"]) || "string"
if ["like", "not like", "starts with", "ends with", "includes"].include?(operator)
ret.push(ops["value"])
else
ret.push(self.quote(ops["value"], col_type.to_s, :sql))
end
elsif ops["count"]
val = self.get_sqltable(ops["count"].split("-").first) + "." + ops["count"].split("-").last
ret << "count(#{val})" #TODO
ret.push(ops["value"])
else
return nil
end
return ret
end
def self.operands2rubyvalue(operator, ops, context_type)
# puts "Enter: operands2rubyvalue: operator: #{operator}, ops: #{ops.inspect}"
operator = operator.downcase
ops["tag"] = ops["field"] if operator == "contains" and !ops["tag"] # process values in contains as tags
ret = []
if ops["tag"] && context_type != "hash"
ref, val = self.value2tag(self.preprocess_managed_tag(ops["tag"]), ops["value"])
fld = val
ret.push(ref ? "<exist ref=#{ref}>#{val}</exist>" : "<exist>#{val}</exist>")
elsif ops["tag"] && context_type == "hash"
# This is only for supporting reporting "display filters"
# In the report object the tag value is actually the description and not the raw tag name.
# So we have to trick it by replacing the value with the description.
description = MiqExpression.get_entry_details(ops["tag"]).inject("") {|s,t|
break(t.first) if t.last == ops["value"]
s
}
val = ops["tag"].split(".").last.split("-").join(".")
fld = "<value type=string>#{val}</value>"
ret.push(fld)
ret.push(self.quote(description, "string"))
elsif ops["field"]
if ops["field"] == "<count>"
ret.push("<count>")
ret.push(ops["value"])
else
case context_type
when "hash"
ref = nil
val = ops["field"].split(".").last.split("-").join(".")
else
ref, val = self.value2tag(ops["field"])
end
col_type = self.get_col_type(ops["field"]) || "string"
col_type = "raw" if operator == "ruby"
fld = val
fld = ref ? "<value ref=#{ref}, type=#{col_type}>#{val}</value>" : "<value type=#{col_type}>#{val}</value>"
ret.push(fld)
if ["like", "not like", "starts with", "ends with", "includes", "regular expression matches", "regular expression does not match", "ruby"].include?(operator)
ret.push(ops["value"])
else
ret.push(self.quote(ops["value"], col_type.to_s))
end
end
elsif ops["count"]
ref, count = self.value2tag(ops["count"])
ret.push(ref ? "<count ref=#{ref}>#{count}</count>" : "<count>#{count}</count>")
ret.push(ops["value"])
elsif ops["regkey"]
ret.push("<registry>#{ops["regkey"].strip} : #{ops["regval"]}</registry>")
if ["like", "not like", "starts with", "ends with", "includes", "regular expression matches", "regular expression does not match"].include?(operator)
ret.push(ops["value"])
elsif operator == "key exists"
ret = "<registry key_exists=1, type=boolean>#{ops["regkey"].strip}</registry> == 'true'"
elsif operator == "value exists"
ret = "<registry value_exists=1, type=boolean>#{ops["regkey"].strip} : #{ops["regval"]}</registry> == 'true'"
else
ret.push(self.quote(ops["value"], "string"))
end
end
return ret
end
def self.quote(val, typ, mode=:ruby)
case typ.to_s
when "string", "text", "boolean", nil
val = "" if val.nil? # treat nil value as empty string
return mode == :sql ? ActiveRecord::Base.connection.quote(val) : "'" + val.to_s.gsub(/'/, "\\\\'") + "'" # escape any embedded single quotes
when "date"
return "nil" if val.blank? # treat nil value as empty string
return mode == :sql ? ActiveRecord::Base.connection.quote(val) : "\'#{val}\'.to_date"
when "datetime"
return "nil" if val.blank? # treat nil value as empty string
return mode == :sql ? ActiveRecord::Base.connection.quote(val.iso8601) : "\'#{val.iso8601}\'.to_time"
when "integer", "decimal", "fixnum"
return val.to_s.to_i_with_method
when "float"
return val.to_s.to_f_with_method
when "numeric_set"
val = val.split(",") if val.kind_of?(String)
v_arr = val.to_miq_a.collect do |v|
v = eval(v) rescue nil if v.kind_of?(String)
v.kind_of?(Range) ? v.to_a : v
end.flatten.compact.uniq.sort
return "[#{v_arr.join(",")}]"
when "string_set"
val = val.split(",") if val.kind_of?(String)
v_arr = val.to_miq_a.collect { |v| "'#{v.to_s.strip}'" }.flatten.uniq.sort
return "[#{v_arr.join(",")}]"
when "raw"
return val
else
return val
end
end
def self.quote_human(val, typ)
case typ.to_s
when "integer", "decimal", "fixnum", "float"
return val.to_i unless val.to_s.number_with_method? || typ.to_s == "float"
if val =~ /^([0-9\.,]+)\.([a-z]+)$/
val = $1; sfx = $2
if sfx.ends_with?("bytes") && FORMAT_BYTE_SUFFIXES.has_key?(sfx.to_sym)
return "#{val} #{FORMAT_BYTE_SUFFIXES[sfx.to_sym]}"
else
return "#{val} #{sfx.titleize}"
end
else
return val
end
when "string", "date", "datetime"
return "\"#{val}\""
else
return self.quote(val, typ)
end
end
def self.re_escape(s)
Regexp.escape(s).gsub(/\//, '\/')
end
def self.preprocess_managed_tag(tag)
path, val = tag.split("-")
path_arr = path.split(".")
if path_arr.include?("managed") || path_arr.include?("user_tag")
name = nil
while path_arr.first != "managed" && path_arr.first != "user_tag" do
name = path_arr.shift
end
return [name].concat(path_arr).join(".") + "-" + val
end
return tag
end
def self.value2tag(tag, val=nil)
val = val.to_s.gsub(/\//, "%2f") unless val.nil? #encode embedded / characters in values since / is used as a tag seperator
v = tag.to_s.split(".").compact.join("/") #split model path and join with "/"
v = v.to_s.split("-").join("/") #split out column name and join with "/"
v = [v, val].join("/") #join with value
v_arr = v.split("/")
ref = v_arr.shift #strip off model (eg. VM)
v_arr[0] = "user" if v_arr.first == "user_tag"
v_arr.unshift("virtual") unless v_arr.first == "managed" || v_arr.first == "user" #add in tag designation
return [ref.downcase, "/" + v_arr.join("/")]
end
def self.normalize_ruby_operator(str)
str = str.upcase
case str
when "EQUAL", "="
"=="
when "NOT"
"!"
when "LIKE", "NOT LIKE", "STARTS WITH", "ENDS WITH", "INCLUDES", "REGULAR EXPRESSION MATCHES"
"=~"
when "REGULAR EXPRESSION DOES NOT MATCH"
"!~"
when "IS NULL", "IS EMPTY"
"=="
when "IS NOT NULL", "IS NOT EMPTY"
"!="
when "BEFORE"
"<"
when "AFTER"
">"
else
str.downcase
end
end
def self.normalize_sql_operator(str)
str = str.upcase
case str
when "EQUAL"
"="
when "!"
"NOT"
when "EXIST"
"CONTAINS"
when "LIKE", "NOT LIKE", "STARTS WITH", "ENDS WITH", "INCLUDES"
"LIKE"
when "IS EMPTY"
"="
when "IS NOT EMPTY"
"!="
when "BEFORE"
"<"
when "AFTER"
">"
else
str
end
end
def self.normalize_operator(str)
str = str.upcase
case str
when "EQUAL"
"="
when "!"
"NOT"
when "EXIST"
"CONTAINS"
else
str
end
end
def self.get_sqltable(path)
# puts "Enter: get_sqltable: path: #{path}"
parts = path.split(".")
name = parts.last
klass = parts.shift.constantize
parts.reverse.each do |assoc|
ref = klass.reflections[assoc.to_sym]
if ref.nil?
klass = nil
break
end
klass = ref.class_name.constantize
end
return klass ? klass.table_name : name.pluralize.underscore
end
def self.base_tables
@@base_tables
end
def self.model_details(model, opts = {:typ=>"all", :include_model=>true, :include_tags=>false, :include_my_tags=>false})
@classifications = nil
model = model.to_s
opts = {:typ=>"all", :include_model=>true}.merge(opts)
if opts[:typ] == "tag"
tags_for_model = self.tag_details(model, model, opts)
result = []
TAG_CLASSES.each_slice(2) {|tc, name|
next if tc.constantize.base_class == model.constantize.base_class
path = [model, name].join(".")
result.concat(self.tag_details(tc, path, opts))
}
@classifications = nil
return tags_for_model.concat(result.sort!{|a,b|a.to_s<=>b.to_s})
end
relats = self.get_relats(model)
result = []
unless opts[:typ] == "count" || opts[:typ] == "find"
result = self.get_column_details(relats[:columns], model, opts).sort!{|a,b|a.to_s<=>b.to_s}
result.concat(self.tag_details(model, model, opts)) if opts[:include_tags] == true
end
result.concat(self._model_details(relats, opts).sort!{|a,b|a.to_s<=>b.to_s})
@classifications = nil
return result
end
def self._model_details(relats, opts)
result = []
relats[:reflections].each {|assoc, ref|
case opts[:typ]
when "count"
result.push(self.get_table_details(ref[:parent][:path])) if ref[:parent][:multivalue]
when "find"
result.concat(self.get_column_details(ref[:columns], ref[:parent][:path], opts)) if ref[:parent][:multivalue]
else
result.concat(self.get_column_details(ref[:columns], ref[:parent][:path], opts))
result.concat(self.tag_details(ref[:parent][:assoc_class], ref[:parent][:path], opts)) if opts[:include_tags] == true
end
result.concat(self._model_details(ref, opts))
}
return result
end
def self.tag_details(model, path, opts)
return [] unless TAG_CLASSES.include?(model)
result = []
@classifications ||= self.get_categories
@classifications.each {|name,cat|
prefix = path.nil? ? "managed" : [path, "managed"].join(".")
field = prefix + "-" + name
result.push([self.value2human(field, opts.merge(:classification => cat)), field])
}
if opts[:include_my_tags] && opts[:userid] && Tag.exists?(["name like ?", "/user/#{opts[:userid]}/%"])
prefix = path.nil? ? "user_tag" : [path, "user_tag"].join(".")
field = prefix + "-" + opts[:userid]
result.push([self.value2human(field, opts), field])
end
result.sort!{|a,b|a.to_s<=>b.to_s}
end
def self.get_relats(model)
@model_relats ||= {}
@model_relats[model] ||= self.build_relats(model)
end
def self.build_lists(model)
$log.info("MIQ(MiqExpression-build_lists) Building lists for: [#{model}]...")
# Build expression lists
[:exp_available_fields, :exp_available_counts, :exp_available_finds].each {|what| self.miq_adv_search_lists(model, what)}
# Build reporting lists
self.reporting_available_fields(model) unless model == model.ends_with?("Trend") || model.ends_with?("Performance") # Can't do trend/perf models at startup
end
def self.miq_adv_search_lists(model, what)
@miq_adv_search_lists ||= {}
@miq_adv_search_lists[model.to_s] ||= {}
case what.to_sym
when :exp_available_fields then @miq_adv_search_lists[model.to_s][:exp_available_fields] ||= MiqExpression.model_details(model, :typ=>"field", :include_model=>true)
when :exp_available_counts then @miq_adv_search_lists[model.to_s][:exp_available_counts] ||= MiqExpression.model_details(model, :typ=>"count", :include_model=>true)
when :exp_available_finds then @miq_adv_search_lists[model.to_s][:exp_available_finds] ||= MiqExpression.model_details(model, :typ=>"find", :include_model=>true)
end
end
def self.reporting_available_fields(model, interval = nil)
@reporting_available_fields ||= {}
if model.to_s == "VimPerformanceTrend"
@reporting_available_fields[model.to_s] ||= {}
@reporting_available_fields[model.to_s][interval.to_s] ||= VimPerformanceTrend.trend_model_details(interval.to_s)
elsif model.ends_with?("Performance")
@reporting_available_fields[model.to_s] ||= {}
@reporting_available_fields[model.to_s][interval.to_s] ||= MiqExpression.model_details(model, :include_model => false, :include_tags => true, :interval =>interval)
elsif model.to_s == "Chargeback"
@reporting_available_fields[model.to_s] ||= MiqExpression.model_details(model, :include_model=>false, :include_tags=>true).select {|c| c.last.ends_with?("_cost") || c.last.ends_with?("_metric") || c.last.ends_with?("-owner_name")}
else
@reporting_available_fields[model.to_s] ||= MiqExpression.model_details(model, :include_model=>false, :include_tags=>true)
end
end
def self.build_relats(model, parent={}, seen=[])
$log.info("MIQ(MiqExpression.build_relats) Building relationship tree for: [#{parent[:path]} => #{model}]...")
model = model_class(model)
parent[:path] ||= model.name
parent[:root] ||= model.name
result = {:columns => model.column_names_with_virtual, :parent => parent}
result[:reflections] = {}
model.reflections_with_virtual.each do |assoc, ref|
next unless @@include_tables.include?(assoc.to_s.pluralize)
next if assoc.to_s.pluralize == "event_logs" && parent[:root] == "Host" && !@@proto
next if assoc.to_s.pluralize == "processes" && parent[:root] == "Host" # Process data not available yet for Host
next if ref.macro == :belongs_to && model.name != parent[:root]
assoc_class = ref.klass.name
new_parent = {
:macro => ref.macro,
:path => [parent[:path], assoc.to_s].join("."),
:assoc => assoc,
:assoc_class => assoc_class,
:root => parent[:root]
}
new_parent[:direction] = new_parent[:macro] == :belongs_to ? :up : :down
new_parent[:multivalue] = [:has_many, :has_and_belongs_to_many].include?(new_parent[:macro])
seen_key = [model.name, assoc].join("_")
unless seen.include?(seen_key) ||
assoc_class == parent[:root] ||
parent[:path].include?(assoc.to_s) ||
parent[:path].include?(assoc.to_s.singularize) ||
parent[:direction] == :up ||
parent[:multivalue]
seen.push(seen_key)
result[:reflections][assoc] = self.build_relats(assoc_class, new_parent, seen)
end
end
result
end
def self.get_table_details(table)
# puts "Enter: get_table_details: model: #{model}, parent: #{parent.inspect}"
[self.value2human(table), table]
end
def self.get_column_details(column_names, parent, opts)
include_model = opts[:include_model]
base_model = parent.split(".").first
excludes = EXCLUDE_COLUMNS
# special case for C&U ad-hoc reporting
if opts[:interval] && opts[:interval] != "daily" && base_model.ends_with?("Performance") && !parent.include?(".")
excludes += ["^min_.*$", "^max_.*$", "^.*derived_storage_.*$", "created_on"]
elsif opts[:interval] && base_model.ends_with?("Performance") && !parent.include?(".")
excludes += ["created_on"]
end
excludes += ["logical_cpus"] if parent == "Vm.hardware"
case base_model
when "VmPerformance"
excludes += ["^.*derived_host_count_off$", "^.*derived_host_count_on$", "^.*derived_vm_count_off$", "^.*derived_vm_count_on$", "^.*derived_storage.*$"]
when "HostPerformance"
excludes += ["^.*derived_host_count_off$", "^.*derived_host_count_on$", "^.*derived_storage.*$", "^abs_.*$"]
when "EmsClusterPerformance"
excludes += ["^.*derived_storage.*$", "sys_uptime_absolute_latest", "^abs_.*$"]
when "StoragePerformance"
includes = ["^.*derived_storage.*$", "^timestamp$", "v_date", "v_time", "resource_name"]
column_names = column_names.collect { |c|
next(c) if includes.include?(c)
c if includes.detect {|incl| c.match(incl) }
}.compact
end
column_names.collect {|c|
# check for direct match first
next if excludes.include?(c) && !EXCLUDE_EXCEPTIONS.include?(c)
# check for regexp match if no direct match
col = c
excludes.each {|excl|
if c.match(excl)
col = nil
break
end
} unless EXCLUDE_EXCEPTIONS.include?(c)
if col
field = parent + "-" + col
[self.value2human(field, :include_model => include_model), field]
end
}.compact
end
def self.get_col_type(field)
model, parts, col = self.parse_field(field)
return :string if model.downcase == "managed" || parts.last == "managed"
return nil unless field.include?("-")
model = self.determine_model(model, parts)
return nil if model.nil?
self.col_type(model, col)
end
def self.col_type(model, col)
model = model_class(model)
col = model.columns_hash_with_virtual[col.to_s]
return col.nil? ? nil : col.type
end
def self.parse_field(field)
col = field.split("-").last
col = col.split("__").first unless col.nil? # throw away pivot table suffix if it exists before looking up type
parts = field.split("-").first.split(".")
model = parts.shift
return model, parts, col
end
NUM_OPERATORS = ["=", "!=", "<", "<=", ">=", ">", "RUBY"]
STRING_OPERATORS = ["=",
"STARTS WITH",
"ENDS WITH",
"INCLUDES",
"IS NULL",
"IS NOT NULL",
"IS EMPTY",
"IS NOT EMPTY",
"REGULAR EXPRESSION MATCHES",
"REGULAR EXPRESSION DOES NOT MATCH",
"RUBY"]
SET_OPERATORS = ["INCLUDES ALL",
"INCLUDES ANY",
"LIMITED TO",
"RUBY"]
REGKEY_OPERATORS = ["KEY EXISTS",
"VALUE EXISTS"]
BOOLEAN_OPERATORS = ["=",
"IS NULL",
"IS NOT NULL"]
DATE_TIME_OPERATORS = ["IS", "BEFORE", "AFTER", "FROM", "IS EMPTY", "IS NOT EMPTY"]
def self.get_col_operators(field)
if field == :count || field == :regkey
col_type = field
else
col_type = self.get_col_type(field.to_s) || :string
end
case col_type.to_s.downcase.to_sym
when :string
return STRING_OPERATORS
when :integer, :float, :fixnum
return NUM_OPERATORS
when :count
return NUM_OPERATORS - ["RUBY"]
when :numeric_set, :string_set
return SET_OPERATORS
when :regkey
return STRING_OPERATORS + REGKEY_OPERATORS
when :boolean
return BOOLEAN_OPERATORS
when :date, :datetime
return DATE_TIME_OPERATORS
else
return STRING_OPERATORS
end
end
STYLE_OPERATORS_EXCLUDES = ["RUBY", "REGULAR EXPRESSION MATCHES", "REGULAR EXPRESSION DOES NOT MATCH", "FROM"]
def self.get_col_style_operators(field)
result = self.get_col_operators(field) - STYLE_OPERATORS_EXCLUDES
end
def self.get_entry_details(field)
ns = field.split("-").first.split(".").last
if ns == "managed"
cat = field.split("-").last
catobj = Classification.find_by_name(cat)
return catobj ? catobj.entries.collect {|e| [e.description, e.name]} : []
elsif ns == "user_tag" || ns == "user"
cat = field.split("-").last
return Tag.find(:all, :conditions => ["name like ?", "/user/#{cat}%"]).collect {|t| [t.name.split("/").last, t.name.split("/").last]}
else
return field
end
end
def self.is_plural?(field)
parts = field.split("-").first.split(".")
macro = nil
model = model_class(parts.shift)
parts.each do |assoc|
ref = model.reflections_with_virtual[assoc.to_sym]
return false if ref.nil?
macro = ref.macro
model = ref.klass
end
[:has_many, :has_and_belongs_to_many].include?(macro)
end
def self.atom_error(field, operator, value)
return false if operator == "DEFAULT" # No validation needed for style DEFAULT operator
value = value.to_s unless value.kind_of?(Array)
dt = case operator.to_s.downcase
when "ruby" # TODO
:ruby
when "regular expression matches", "regular expression does not match" #TODO
:regexp
else
if field == :count
:integer
else
col_info = self.get_col_info(field)
[:bytes, :megabytes].include?(col_info[:format_sub_type]) ? :integer : col_info[:data_type]
end
end
case dt
when :string, :text
return false
when :integer, :fixnum, :decimal, :float
return false if self.send((dt == :float ? :is_numeric? : :is_integer?), value)
dt_human = dt == :float ? "Number" : "Integer"
return "#{dt_human} value must not be blank" if value.gsub(/,/, "").blank?
if value.include?(".") && (value.split(".").last =~ /([a-z]+)/i)
sfx = $1
sfx = sfx.ends_with?("bytes") && FORMAT_BYTE_SUFFIXES.has_key?(sfx.to_sym) ? FORMAT_BYTE_SUFFIXES[sfx.to_sym] : sfx.titleize
value = "#{value.split(".")[0..-2].join(".")} #{sfx}"
end
return "Value '#{value}' is not a valid #{dt_human}"
when :date, :datetime
return false if operator.downcase.include?("empty")
values = value.to_miq_a
return "No Date/Time value specified" if values.empty? || values.include?(nil)
return "Two Date/Time values must be specified" if operator.downcase == "from" && values.length < 2
values_converted = values.collect do |v|
return "Date/Time value must not be blank" if value.blank?
v_cvt = self.normalize_date_time(v, "UTC") rescue nil
return "Value '#{v}' is not valid" if v_cvt.nil?
v_cvt
end
return "Invalid Date/Time range, #{values[1]} comes before #{values[0]}" if values_converted.length > 1 && values_converted[0] > values_converted[1]
return false
when :boolean
return "Value must be true or false" unless operator.downcase.include?("null") || ["true", "false"].include?(value)
return false
when :regexp
begin
Regexp.new(value).match("foo")
rescue => err
return "Regular expression '#{value}' is invalid, '#{err.message}'"
end
return false
when :ruby
return "Ruby Script must not be blank" if value.blank?
return false
else
return false
end
return "Value '#{value}' must be in the form of #{FORMAT_SUB_TYPES[dt][:short_name]}"
end
def self.get_categories
classifications = Classification.in_my_region.hash_all_by_type_and_name(:show => true)
categories_with_entries = classifications.reject { |k, v| !v.has_key?(:entry) }
categories_with_entries.each_with_object({}) do |(name, hash), categories|
categories[name] = hash[:category]
end
end
def self.model_class(model)
# TODO: the temporary cache should be removed after widget refactoring
@@model_class ||= Hash.new { |h, m| h[m] = m.is_a?(Class) ? m: m.to_s.singularize.camelize.constantize rescue nil }
@@model_class[model]
end
def self.is_integer?(n)
n = n.to_s
n2 = n.gsub(/,/, "") # strip out commas
begin
Integer n2
return true
rescue
return false unless n.number_with_method?
begin
n2 = n.to_f_with_method
return (n2.to_i == n2)
rescue
return false
end
end
end
def self.is_numeric?(n)
n = n.to_s
n2 = n.gsub(/,/, "") # strip out commas
begin
Float n2
return true
rescue
return false unless n.number_with_method?
begin
n.to_f_with_method
return true
rescue
return false
end
end
end
# Is an MiqExpression or an expression hash a quick_search
def self.quick_search?(exp)
return exp.quick_search? if exp.is_a?(self)
return self._quick_search?(exp)
end
def quick_search?
self.class._quick_search?(self.exp) # Pass the exp hash
end
# Is an expression hash a quick search?
def self._quick_search?(e)
if e.is_a?(Array)
e.each { |e_exp| return true if self._quick_search?(e_exp) }
elsif e.is_a?(Hash)
return true if e["value"] == :user_input
e.each_value {|e_exp| return true if self._quick_search?(e_exp)}
end
return false
end
private
def self.determine_model(model, parts)
model = model_class(model)
return nil if model.nil?
parts.each do |assoc|
ref = model.reflections_with_virtual[assoc.to_sym]
return nil if ref.nil?
model = ref.klass
end
model
end
end #class MiqExpression
Add MiqExpression.determine_relat_path
to build the model relationship path correctly if class_name is specified for an association.
The :parent,:path field built in the model relationship tree is used to populate the Available Fields in reporting.
https://bugzilla.redhat.com/show_bug.cgi?id=1133132
class MiqExpression
attr_accessor :exp, :context_type, :preprocess_options
@@proto = VMDB::Config.new("vmdb").config[:product][:proto]
@@base_tables = %w{
AuditEvent
AvailabilityZone
BottleneckEvent
Chargeback
CloudResourceQuota
CloudTenant
Compliance
EmsCluster
EmsClusterPerformance
EmsEvent
ExtManagementSystem
Flavor
Host
HostPerformance
MiqGroup
MiqRegion
MiqRequest
MiqServer
MiqTemplate
MiqWorker
OntapFileShare
OntapLogicalDisk
OntapStorageSystem
OntapStorageVolume
OntapVolumeMetricsRollup
PolicyEvent
Repository
ResourcePool
SecurityGroup
Service
ServiceTemplate
Storage
StorageFile
StoragePerformance
TemplateCloud
TemplateInfra
User
VimPerformanceTrend
Vm
VmCloud
VmInfra
VmPerformance
Zone
}
if VdiFarm.is_available?
@@base_tables += %w{
VdiController
VdiDesktop
VdiDesktopPool
VdiEndpointDevice
VdiFarm
VdiSession
VdiUser
VmVdi
}
end
@@include_tables = %w{
advanced_settings
audit_events
availability_zones
cloud_resource_quotas
cloud_tenants
compliances
compliance_details
disks
ems_events
ems_clusters
ems_custom_attributes
evm_owners
event_logs
ext_management_systems
filesystem_drivers
filesystems
firewall_rules
flavors
groups
guest_applications
hardwares
hosts
host_services
kernel_drivers
lans
last_compliances
linux_initprocesses
miq_actions
miq_approval_stamps
miq_custom_attributes
miq_policy_sets
miq_provisions
miq_regions
miq_requests
miq_scsi_luns
miq_servers
miq_workers
ontap_concrete_extents
ontap_file_shares
ontap_logical_disks
ontap_plex_extents
ontap_raid_group_extents
ontap_storage_systems
ontap_storage_volumes
partitions
ports
processes
miq_provision_templates
miq_provision_vms
miq_templates
networks
nics
operating_systems
patches
registry_items
repositories
resource_pools
security_groups
service_templates
services
snapshots
storages
storage_adapters
storage_files
switches
users
vms
volumes
win32_services
zones
storage_systems
file_systems
hosted_file_shares
file_shares
logical_disks
storage_volumes
base_storage_extents
top_storage_extents
}
if VdiFarm.is_available?
@@include_tables += %w{
vdi_controllers
vdi_desktop_pools
vdi_desktops
vdi_endpoint_devices
vdi_farms
vdi_sessions
vdi_users
}
@@include_tables += %w{ldaps} if VdiFarm::MGMT_ENABLED == true
end
EXCLUDE_COLUMNS = %w{
^.*_id$
^blackbox_.*$
^id$
^min_derived_storage.*$
^max_derived_storage.*$
assoc_ids
capture_interval
filters
icon
intervals_in_rollup
max_cpu_ready_delta_summation
max_cpu_system_delta_summation
max_cpu_used_delta_summation
max_cpu_wait_delta_summation
max_derived_cpu_available
max_derived_cpu_reserved
max_derived_memory_available
max_derived_memory_reserved
memory_usage
min_cpu_ready_delta_summation
min_cpu_system_delta_summation
min_cpu_used_delta_summation
min_cpu_wait_delta_summation
min_derived_memory_available
min_derived_memory_reserved
min_derived_cpu_available
min_derived_cpu_reserved
min_max
options
password
policy_settings
^reserved$
resource_id
settings
tag_names
v_qualified_desc
disk_io_cost
disk_io_metric
net_io_cost
net_io_metric
fixed_2_cost
}
EXCLUDE_EXCEPTIONS = %w{
capacity_profile_1_memory_per_vm_with_min_max
capacity_profile_1_vcpu_per_vm_with_min_max
capacity_profile_2_memory_per_vm_with_min_max
capacity_profile_2_vcpu_per_vm_with_min_max
chain_id
guid
}
TAG_CLASSES = [
"EmsCloud", "ext_management_system",
"EmsCluster", "ems_cluster",
"EmsInfra", "ext_management_system",
"Host", "host",
"MiqGroup", "miq_group",
"MiqTemplate", "miq_template",
"Repository", "repository",
"ResourcePool", "resource_pool",
"Service", "service",
"Storage", "storage",
"TemplateCloud", "miq_template",
"TemplateInfra", "miq_template",
"User", "user",
"Vm", "vm",
"VmCloud", "vm",
"VmInfra", "vm"
]
FORMAT_SUB_TYPES = {
:boolean => {
:short_name => "Boolean",
:title => "Enter true or false"
},
:bytes => {
:short_name => "Bytes",
:title => "Enter the number of Bytes",
:units => [
["Bytes", :bytes],
["KB", :kilobytes],
["MB", :megabytes],
["GB", :gigabytes],
["TB", :terabytes]
]
},
:date => {
:short_name => "Date",
:title => "Click to Choose a Date"
},
:datetime => {
:short_name => "Date / Time",
:title => "Click to Choose a Date / Time"
},
:float => {
:short_name => "Number",
:title => "Enter a Number (like 12.56)"
},
:gigabytes => {
:short_name => "Gigabytes",
:title => "Enter the number of Gigabytes"
},
:integer => {
:short_name => "Integer",
:title => "Enter an Integer"
},
:kbps => {
:short_name => "KBps",
:title => "Enter the Kilobytes per second"
},
:kilobytes => {
:short_name => "Kilobytes",
:title => "Enter the number of Kilobytes"
},
:megabytes => {
:short_name => "Megabytes",
:title => "Enter the number of Megabytes"
},
:mhz => {
:short_name => "Mhz",
:title => "Enter the number of Megahertz"
},
:numeric_set => {
:short_name => "Number List",
:title => "Enter a list of numbers separated by commas"
},
:percent => {
:short_name => "Percent",
:title => "Enter a Percent (like 12.5)",
},
:regex => {
:short_name => "Regular Expression",
:title => "Enter a Regular Expression"
},
:ruby => {
:short_name => "Ruby Script",
:title => "Enter one or more lines of Ruby Script"
},
:string => {
:short_name => "Text String",
:title => "Enter a Text String"
},
:string_set => {
:short_name => "String List",
:title => "Enter a list of text strings separated by commas"
}
}
FORMAT_SUB_TYPES[:fixnum] = FORMAT_SUB_TYPES[:decimal] = FORMAT_SUB_TYPES[:integer]
FORMAT_SUB_TYPES[:mhz_avg] = FORMAT_SUB_TYPES[:mhz]
FORMAT_SUB_TYPES[:text] = FORMAT_SUB_TYPES[:string]
FORMAT_BYTE_SUFFIXES = FORMAT_SUB_TYPES[:bytes][:units].inject({}) {|h, (v,k)| h[k] = v; h}
def initialize(exp, ctype = nil)
@exp = exp
@context_type = ctype
end
def self.to_human(exp)
if exp.is_a?(self)
exp.to_human
else
if exp.is_a?(Hash)
case exp["mode"]
when "tag_expr"
return exp["expr"]
when "tag"
tag = [exp["ns"], exp["tag"]].join("/")
if exp["include"] == "none"
return "Not Tagged With #{tag}"
else
return "Tagged With #{tag}"
end
when "script"
if exp["expr"] == "true"
return "Always True"
else
return exp["expr"]
end
else
return self.new(exp).to_human
end
else
return exp.inspect
end
end
end
def to_human
self.class._to_human(@exp)
end
def self._to_human(exp, options={})
return exp unless exp.is_a?(Hash) || exp.is_a?(Array)
keys = exp.keys
keys.delete(:token)
operator = keys.first
case operator.downcase
when "like", "not like", "starts with", "ends with", "includes", "includes any", "includes all", "includes only", "limited to", "regular expression", "regular expression matches", "regular expression does not match", "equal", "=", "<", ">", ">=", "<=", "!=", "before", "after"
operands = self.operands2humanvalue(exp[operator], options)
clause = operands.join(" #{self.normalize_operator(operator)} ")
when "and", "or"
clause = "( " + exp[operator].collect {|operand| self._to_human(operand)}.join(" #{self.normalize_operator(operator)} ") + " )"
when "not", "!"
clause = self.normalize_operator(operator) + " ( " + self._to_human(exp[operator]) + " )"
when "is null", "is not null", "is empty", "is not empty"
clause = self.operands2humanvalue(exp[operator], options).first + " " + operator
when "contains"
operands = self.operands2humanvalue(exp[operator], options)
clause = operands.join(" #{self.normalize_operator(operator)} ")
when "find"
# FIND Vm.users-name = 'Administrator' CHECKALL Vm.users-enabled = 1
check = nil
check = "checkall" if exp[operator].include?("checkall")
check = "checkany" if exp[operator].include?("checkany")
check = "checkcount" if exp[operator].include?("checkcount")
raise "expression malformed, must contain one of 'checkall', 'checkany', 'checkcount'" unless check
check =~ /^check(.*)$/; mode = $1.upcase
clause = "FIND" + " " + self._to_human(exp[operator]["search"]) + " CHECK " + mode + " " + self._to_human(exp[operator][check], :include_table => false).strip
when "key exists"
clause = "KEY EXISTS #{exp[operator]['regkey']}"
when "value exists"
clause = "VALUE EXISTS #{exp[operator]['regkey']} : #{exp[operator]['regval']}"
when "ruby"
operands = self.operands2humanvalue(exp[operator], options)
operands[1] = "<RUBY Expression>"
clause = operands.join(" #{self.normalize_operator(operator)} \n")
when "is"
operands = self.operands2humanvalue(exp[operator], options)
clause = "#{operands.first} #{operator} #{operands.last}"
when "between dates", "between times"
col_name = exp[operator]["field"]
col_type = self.get_col_type(col_name)
col_human, dumy = self.operands2humanvalue(exp[operator], options)
vals_human = exp[operator]["value"].collect {|v| self.quote_human(v, col_type)}
clause = "#{col_human} #{operator} #{vals_human.first} AND #{vals_human.last}"
when "from"
col_name = exp[operator]["field"]
col_type = self.get_col_type(col_name)
col_human, dumy = self.operands2humanvalue(exp[operator], options)
vals_human = exp[operator]["value"].collect {|v| self.quote_human(v, col_type)}
clause = "#{col_human} #{operator} #{vals_human.first} THROUGH #{vals_human.last}"
end
# puts "clause: #{clause}"
return clause
end
def to_ruby(tz=nil)
tz ||= "UTC"
@ruby ||= self.class._to_ruby(@exp.deep_clone, @context_type, tz)
return @ruby.dup
end
def self._to_ruby(exp, context_type, tz)
return exp unless exp.is_a?(Hash) || exp.is_a?(Array)
operator = exp.keys.first
case operator.downcase
when "equal", "=", "<", ">", ">=", "<=", "!=", "before", "after"
col_type = self.get_col_type(exp[operator]["field"]) if exp[operator]["field"]
return self._to_ruby({"date_time_with_logical_operator" => exp}, context_type, tz) if col_type == :date || col_type == :datetime
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = operands.join(" #{self.normalize_ruby_operator(operator)} ")
when "includes all"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = "(#{operands[0]} & #{operands[1]}) == #{operands[1]}"
when "includes any"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = "(#{operands[1]} - #{operands[0]}) != #{operands[1]}"
when "includes only", "limited to"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = "(#{operands[0]} - #{operands[1]}) == []"
when "like", "not like", "starts with", "ends with", "includes"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
case operator.downcase
when "starts with"
operands[1] = "/^" + self.re_escape(operands[1].to_s) + "/"
when "ends with"
operands[1] = "/" + self.re_escape(operands[1].to_s) + "$/"
else
operands[1] = "/" + self.re_escape(operands[1].to_s) + "/"
end
clause = operands.join(" #{self.normalize_ruby_operator(operator)} ")
clause = "!(" + clause + ")" if operator.downcase == "not like"
when "regular expression matches", "regular expression does not match"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
operands[1] = "/" + operands[1].to_s + "/" unless operands[1].starts_with?("/") && (operands[1].ends_with?("/") || operands[1][-2..-2] == "/")
clause = operands.join(" #{self.normalize_ruby_operator(operator)} ")
when "and", "or"
clause = "(" + exp[operator].collect {|operand| self._to_ruby(operand, context_type, tz)}.join(" #{self.normalize_ruby_operator(operator)} ") + ")"
when "not", "!"
clause = self.normalize_ruby_operator(operator) + "(" + self._to_ruby(exp[operator], context_type, tz) + ")"
when "is null", "is not null", "is empty", "is not empty"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = operands.join(" #{self.normalize_ruby_operator(operator)} ")
when "contains"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
clause = operands.join(" #{self.normalize_operator(operator)} ")
when "find"
# FIND Vm.users-name = 'Administrator' CHECKALL Vm.users-enabled = 1
check = nil
check = "checkall" if exp[operator].include?("checkall")
check = "checkany" if exp[operator].include?("checkany")
if exp[operator].include?("checkcount")
check = "checkcount"
op = exp[operator][check].keys.first
exp[operator][check][op]["field"] = "<count>"
end
raise "expression malformed, must contain one of 'checkall', 'checkany', 'checkcount'" unless check
check =~ /^check(.*)$/; mode = $1.downcase
clause = "<find><search>" + self._to_ruby(exp[operator]["search"], context_type, tz) + "</search><check mode=#{mode}>" + self._to_ruby(exp[operator][check], context_type, tz) + "</check></find>"
when "key exists"
clause = self.operands2rubyvalue(operator, exp[operator], context_type)
when "value exists"
clause = self.operands2rubyvalue(operator, exp[operator], context_type)
when "ruby"
operands = self.operands2rubyvalue(operator, exp[operator], context_type)
col_type = self.get_col_type(exp[operator]["field"]) || "string"
clause = "__start_ruby__ __start_context__#{operands[0]}__type__#{col_type}__end_context__ __start_script__#{operands[1]}__end_script__ __end_ruby__"
when "is"
col_name = exp[operator]["field"]
col_ruby, dummy = self.operands2rubyvalue(operator, {"field" => col_name}, context_type)
col_type = self.get_col_type(col_name)
value = exp[operator]["value"]
if col_type == :date
if self.date_time_value_is_relative?(value)
start_val = self.quote(self.normalize_date_time(value, "UTC", "beginning").to_date, :date)
end_val = self.quote(self.normalize_date_time(value, "UTC", "end").to_date, :date)
clause = "val=#{col_ruby}; !val.nil? && val.to_date >= #{start_val} && val.to_date <= #{end_val}"
else
value = self.quote(self.normalize_date_time(value, "UTC", "beginning").to_date, :date)
clause = "val=#{col_ruby}; !val.nil? && val.to_date == #{value}"
end
else
start_val = self.quote(self.normalize_date_time(value, tz, "beginning").utc, :datetime)
end_val = self.quote(self.normalize_date_time(value, tz, "end").utc, :datetime)
clause = "val=#{col_ruby}; !val.nil? && val.to_time >= #{start_val} && val.to_time <= #{end_val}"
end
when "from"
col_name = exp[operator]["field"]
col_ruby, dummy = self.operands2rubyvalue(operator, {"field" => col_name}, context_type)
col_type = self.get_col_type(col_name)
start_val, end_val = exp[operator]["value"]
start_val = self.quote(self.normalize_date_time(start_val, tz, "beginning").utc, :datetime)
end_val = self.quote(self.normalize_date_time(end_val, tz, "end").utc, :datetime)
clause = "val=#{col_ruby}; !val.nil? && val.to_time >= #{start_val} && val.to_time <= #{end_val}"
when "date_time_with_logical_operator"
exp = exp[operator]
operator = exp.keys.first
col_name = exp[operator]["field"]
col_type = self.get_col_type(col_name)
col_ruby, dummy = self.operands2rubyvalue(operator, {"field" => col_name}, context_type)
normalized_operator = self.normalize_ruby_operator(operator)
mode = case normalized_operator
when ">", "<=" then "end" # (> <date> 23::59:59), (<= <date> 23::59:59)
when "<", ">=" then "beginning" # (< <date> 00::00:00), (>= <date> 00::00:00)
end
val = self.normalize_date_time(exp[operator]["value"], tz, mode)
clause = "val=#{col_ruby}; !val.nil? && val.to_time #{normalized_operator} #{self.quote(val.utc, :datetime)}"
else
raise "operator '#{operator}' is not supported"
end
# puts "clause: #{clause}"
return clause
end
def self.normalize_date_time(rel_time, tz, mode="beginning")
# time_spec =
# <value> <interval> Ago
# "Today"
# "Yesterday"
# "Now"
# "Last Week"
# "Last Month"
# "Last Quarter"
# "This Week"
# "This Month"
# "This Quarter"
rt = rel_time.downcase
if rt.starts_with?("this") || rt.starts_with?("last")
# Convert these into the time spec form: <value> <interval> Ago
value, interval = rt.split
rt = "#{value == "this" ? 0 : 1} #{interval} ago"
end
if rt.ends_with?("ago")
# Time spec <value> <interval> Ago
value, interval, ago = rt.split
interval = interval.pluralize
if interval == "hours"
self.beginning_or_end_of_hour(value.to_i.hours.ago.in_time_zone(tz), mode)
elsif interval == "quarters"
ts = Time.now.in_time_zone(tz).beginning_of_quarter
(ts - (value.to_i * 3.months)).send("#{mode}_of_quarter")
else
value.to_i.send(interval).ago.in_time_zone(tz).send("#{mode}_of_#{interval.singularize}")
end
elsif rt == "today"
Time.now.in_time_zone(tz).send("#{mode}_of_day")
elsif rt == "yesterday"
1.day.ago.in_time_zone(tz).send("#{mode}_of_day")
elsif rt == "now"
self.beginning_or_end_of_hour(Time.now.in_time_zone(tz), mode)
else
# Assume it's an absolute date or time
value_is_date = !rel_time.include?(":")
ts = Time.use_zone(tz) { Time.zone.parse(rel_time) }
ts = ts.send("#{mode}_of_day") if mode && value_is_date
ts
end
end
def self.beginning_or_end_of_hour(ts, mode)
ts_str = ts.iso8601
ts_str[14..18] = mode == "end" ? "59:59" : "00:00"
Time.parse(ts_str)
end
def self.date_time_value_is_relative?(value)
v = value.downcase
v.starts_with?("this") || v.starts_with?("last") || v.ends_with?("ago") || ["today", "yesterday", "now"].include?(v)
end
def to_sql(tz=nil)
tz ||= "UTC"
@pexp, attrs = self.preprocess_for_sql(@exp.deep_clone)
sql = self._to_sql(@pexp, tz)
incl = self.includes_for_sql unless sql.blank?
return [sql, incl, attrs]
end
def _to_sql(exp, tz)
return exp unless exp.is_a?(Hash) || exp.is_a?(Array)
operator = exp.keys.first
return if operator.nil?
case operator.downcase
when "equal", "=", "<", ">", ">=", "<=", "!=", "before", "after"
col_type = self.class.get_col_type(exp[operator]["field"]) if exp[operator]["field"]
return self._to_sql({"date_time_with_logical_operator" => exp}, tz) if col_type == :date || col_type == :datetime
operands = self.class.operands2sqlvalue(operator, exp[operator])
clause = operands.join(" #{self.class.normalize_sql_operator(operator)} ")
when "like", "not like", "starts with", "ends with", "includes"
operands = self.class.operands2sqlvalue(operator, exp[operator])
case operator.downcase
when "starts with"
operands[1] = "'" + operands[1].to_s + "%'"
when "ends with"
operands[1] = "'%" + operands[1].to_s + "'"
when "like", "not like", "includes"
operands[1] = "'%" + operands[1].to_s + "%'"
end
clause = operands.join(" #{self.class.normalize_sql_operator(operator)} ")
clause = "!(" + clause + ")" if operator.downcase == "not like"
when "and", "or"
operands = exp[operator].collect {|operand|
o = self._to_sql(operand, tz)
o.blank? ? nil : o
}.compact
if operands.length > 1
clause = "(" + operands.join(" #{self.class.normalize_sql_operator(operator)} ") + ")"
elsif operands.length == 1 # Operands may have been stripped out during pre-processing
clause = "(" + operands.first + ")"
else # All operands may have been stripped out during pre-processing
clause = nil
end
when "not", "!"
clause = self.class.normalize_sql_operator(operator) + " " + self._to_sql(exp[operator], tz)
when "is null", "is not null"
operands = self.class.operands2sqlvalue(operator, exp[operator])
clause = "(#{operands[0]} #{self.class.normalize_sql_operator(operator)})"
when "is empty", "is not empty"
col = exp[operator]["field"]
col_type = self.col_details[col].nil? ? :string : self.col_details[col][:data_type]
operands = self.class.operands2sqlvalue(operator, exp[operator])
clause = "(#{operands[0]} #{operator.sub(/empty/i, "NULL")})"
if col_type == :string
conjunction = (operator.downcase == 'is empty') ? 'OR' : 'AND'
clause = "(#{clause} #{conjunction} (#{operands[0]} #{self.class.normalize_sql_operator(operator)} ''))"
end
when "contains"
# Only support for tags of the main model
if exp[operator].has_key?("tag")
klass, ns = exp[operator]["tag"].split(".")
ns = "/" + ns.split("-").join("/")
ns = ns.sub(/(\/user_tag\/)/, "/user/") # replace with correct namespace for user tags
tag = exp[operator]["value"]
klass = klass.constantize
ids = klass.find_tagged_with(:any => tag, :ns => ns).pluck(:id)
clause = "(#{klass.send(:sanitize_sql_for_conditions, :id => ids)})"
else
db, field = exp[operator]["field"].split(".")
model = db.constantize
assoc, field = field.split("-")
ref = model.reflections[assoc.to_sym]
inner_where = "#{field} = '#{exp[operator]["value"]}'"
if cond = ref.options.fetch(:conditions, nil) # Include ref.options[:conditions] in inner select if exists
cond = ref.options[:class_name].constantize.send(:sanitize_sql_for_assignment, cond)
inner_where = "(#{inner_where}) AND (#{cond})"
end
clause = "#{model.table_name}.id IN (SELECT DISTINCT #{ref.foreign_key} FROM #{ref.table_name} WHERE #{inner_where})"
end
when "is"
col_name = exp[operator]["field"]
col_sql, dummy = self.class.operands2sqlvalue(operator, {"field" => col_name})
col_type = self.class.get_col_type(col_name)
value = exp[operator]["value"]
if col_type == :date
if self.class.date_time_value_is_relative?(value)
start_val = self.class.quote(self.class.normalize_date_time(value, "UTC", "beginning").to_date, :date, :sql)
end_val = self.class.quote(self.class.normalize_date_time(value, "UTC", "end").to_date, :date, :sql)
clause = "#{col_sql} BETWEEN #{start_val} AND #{end_val}"
else
value = self.class.quote(self.class.normalize_date_time(value, "UTC", "beginning").to_date, :date, :sql)
clause = "#{col_sql} = #{value}"
end
else
start_val = self.class.quote(self.class.normalize_date_time(value, tz, "beginning").utc, :datetime, :sql)
end_val = self.class.quote(self.class.normalize_date_time(value, tz, "end").utc, :datetime, :sql)
clause = "#{col_sql} BETWEEN #{start_val} AND #{end_val}"
end
when "from"
col_name = exp[operator]["field"]
col_sql, dummy = self.class.operands2sqlvalue(operator, {"field" => col_name})
col_type = self.class.get_col_type(col_name)
start_val, end_val = exp[operator]["value"]
start_val = self.class.quote(self.class.normalize_date_time(start_val, tz, "beginning").utc, :datetime, :sql)
end_val = self.class.quote(self.class.normalize_date_time(end_val, tz, "end").utc, :datetime, :sql)
clause = "#{col_sql} BETWEEN #{start_val} AND #{end_val}"
when "date_time_with_logical_operator"
exp = exp[operator]
operator = exp.keys.first
col_name = exp[operator]["field"]
col_type = self.class.get_col_type(col_name)
col_sql, dummy = self.class.operands2sqlvalue(operator, {"field" => col_name})
normalized_operator = self.class.normalize_sql_operator(operator)
mode = case normalized_operator
when ">", "<=" then "end" # (> <date> 23::59:59), (<= <date> 23::59:59)
when "<", ">=" then "beginning" # (< <date> 00::00:00), (>= <date> 00::00:00)
end
val = self.class.normalize_date_time(exp[operator]["value"], tz, mode)
clause = "#{col_sql} #{normalized_operator} #{self.class.quote(val.utc, :datetime, :sql)}"
else
raise "operator '#{operator}' is not supported"
end
# puts "clause: #{clause}"
return clause
end
def preprocess_for_sql(exp, attrs=nil)
attrs ||= {:supported_by_sql => true}
operator = exp.keys.first
case operator.downcase
when "and"
exp[operator].dup.each { |atom| self.preprocess_for_sql(atom, attrs)}
exp[operator] = exp[operator].collect {|o| o.blank? ? nil : o}.compact # Clean out empty operands
exp.delete(operator) if exp[operator].empty?
when "or"
or_attrs = {:supported_by_sql => true}
exp[operator].each_with_index { |atom,i|
self.preprocess_for_sql(atom, or_attrs)
exp[operator][i] = nil if atom.blank?
}
exp[operator].compact!
attrs.merge!(or_attrs)
exp.delete(operator) if !or_attrs[:supported_by_sql] || exp[operator].empty? # Clean out unsupported or empty operands
when "not"
self.preprocess_for_sql(exp[operator], attrs)
exp.delete(operator) if exp[operator].empty? # Clean out empty operands
else
# check operands to see if they can be represented in sql
unless sql_supports_atom?(exp)
attrs[:supported_by_sql] = false
exp.delete(operator)
end
end
return exp.empty? ? [nil, attrs] : [exp, attrs]
end
def sql_supports_atom?(exp)
operator = exp.keys.first
case operator.downcase
when "contains"
if exp[operator].keys.include?("tag") && exp[operator]["tag"].split(".").length == 2 # Only support for tags of the main model
return true
elsif exp[operator].keys.include?("field") && exp[operator]["field"].split(".").length == 2
db, field = exp[operator]["field"].split(".")
assoc, field = field.split("-")
ref = db.constantize.reflections[assoc.to_sym]
return false unless ref
return false unless ref.macro == :has_many || ref.macro == :has_one
return false if ref.options && ref.options.has_key?(:as)
return field_in_sql?(exp[operator]["field"])
else
return false
end
when "includes"
# Support includes operator using "LIKE" only if first operand is in main table
if exp[operator].has_key?("field") && (!exp[operator]["field"].include?(".") || (exp[operator]["field"].include?(".") && exp[operator]["field"].split(".").length == 2))
return field_in_sql?(exp[operator]["field"])
else
# TODO: Support includes operator for sub-sub-tables
return false
end
when "find", "regular expression matches", "regular expression does not match", "key exists", "value exists", "ruby"
return false
else
# => false if operand is a tag
return false if exp[operator].keys.include?("tag")
# => TODO: support count of child relationship
return false if exp[operator].has_key?("count")
return field_in_sql?(exp[operator]["field"])
end
end
def field_in_sql?(field)
# => false if operand is from a virtual reflection
return false if self.field_from_virtual_reflection?(field)
# => false if operand if a virtual coulmn
return false if self.field_is_virtual_column?(field)
# => false if excluded by special case defined in preprocess options
return false if self.field_excluded_by_preprocess_options?(field)
return true
end
def field_from_virtual_reflection?(field)
self.col_details[field][:virtual_reflection]
end
def field_is_virtual_column?(field)
self.col_details[field][:virtual_column]
end
def field_excluded_by_preprocess_options?(field)
self.col_details[field][:excluded_by_preprocess_options]
end
def col_details
@col_details ||= self.class.get_cols_from_expression(@exp, @preprocess_options)
end
def includes_for_sql
result = {}
self.col_details.each_value do |v|
self.class.deep_merge_hash(result, v[:include])
end
return result
end
def columns_for_sql(exp=nil, result = nil)
exp ||= self.exp
result ||= []
return result unless exp.kind_of?(Hash)
operator = exp.keys.first
if exp[operator].kind_of?(Hash) && exp[operator].has_key?("field")
unless exp[operator]["field"] == "<count>" || self.field_from_virtual_reflection?(exp[operator]["field"]) || self.field_is_virtual_column?(exp[operator]["field"])
col = exp[operator]["field"]
if col.include?(".")
col = col.split(".").last
col = col.sub("-", ".")
else
col = col.split("-").last
end
result << col
end
else
exp[operator].dup.to_miq_a.each { |atom| self.columns_for_sql(atom, result) }
end
return result.compact.uniq
end
def self.deep_merge_hash(hash1,hash2)
return hash1 if hash2.nil?
hash2.each_key do |k1|
if hash1.key?(k1)
deep_merge_hash(hash1[k1],hash2[k1])
else
hash1[k1] = hash2[k1]
end
end
end
def self.merge_where_clauses_and_includes(where_clauses, includes)
[self.merge_where_clauses(*where_clauses), self.merge_includes(*includes)]
end
def self.merge_where_clauses(*list)
l = list.compact.collect do |s|
s = MiqReport.send(:sanitize_sql_for_conditions, s)
"(#{s})"
end
return l.empty? ? nil : l.join(" AND ")
end
def self.merge_includes(*incl_list)
return nil if incl_list.blank?
result = {}
incl_list.each do |i|
self.deep_merge_hash(result, i)
end
return result
end
def self.get_cols_from_expression(exp, options={})
result = {}
if exp.kind_of?(Hash)
if exp.has_key?("field")
result[exp["field"]] = self.get_col_info(exp["field"], options) unless exp["field"] == "<count>"
elsif exp.has_key?("count")
result[exp["count"]] = self.get_col_info(exp["count"], options)
elsif exp.has_key?("tag")
# ignore
else
exp.each_value { |v| result.merge!(self.get_cols_from_expression(v, options)) }
end
elsif exp.kind_of?(Array)
exp.each {|v| result.merge!(self.get_cols_from_expression(v, options)) }
end
return result
end
def self.get_col_info(field, options={})
result ||= {:data_type => nil, :virtual_reflection => false, :virtual_column => false, :excluded_by_preprocess_options => false, :tag => false, :include => {}}
col = field.split("-").last if field.include?("-")
parts = field.split("-").first.split(".")
model = parts.shift
if model.downcase == "managed" || parts.last == "managed"
result[:data_type] = :string
result[:tag] = true
return result
end
model = model_class(model)
cur_incl = result[:include]
parts.each do |assoc|
assoc = assoc.to_sym
ref = model.reflections_with_virtual[assoc]
result[:virtual_reflection] = true if ref.kind_of?(VirtualReflection)
unless result[:virtual_reflection]
cur_incl[assoc] ||= {}
cur_incl = cur_incl[assoc]
end
unless ref
result[:virtual_reflection] = true
result[:virtual_column] = true
return result
end
model = ref.klass
end
if col
result[:data_type] = self.col_type(model, col)
result[:format_sub_type] = MiqReport::FORMAT_DEFAULTS_AND_OVERRIDES[:sub_types_by_column][col.to_sym] || result[:data_type]
result[:virtual_column] = true if model.virtual_columns_hash.include?(col.to_s)
result[:excluded_by_preprocess_options] = self.exclude_col_by_preprocess_options?(col, options)
end
return result
end
def self.exclude_col_by_preprocess_options?(col, options)
return false unless options.kind_of?(Hash)
if options[:vim_performance_daily_adhoc]
return VimPerformanceDaily.excluded_cols_for_expressions.include?(col.to_sym)
end
return false
end
def self.evaluate(expression, obj, inputs={})
ruby_exp = expression.is_a?(Hash) ? self.new(expression).to_ruby : expression.to_ruby
$log.debug("MIQ(Expression-evaluate) Expression before substitution: #{ruby_exp}")
subst_expr = self.subst(ruby_exp, obj, inputs)
$log.debug("MIQ(Expression-evaluate) Expression after substitution: #{subst_expr}")
result = eval(subst_expr) ? true : false
$log.debug("MIQ(Expression-evaluate) Expression evaluation result: [#{result}]")
return result
end
def evaluate(obj, inputs={})
self.class.evaluate(self, obj, inputs)
end
def self.evaluate_atoms(exp, obj, inputs={})
exp = exp.is_a?(self) ? copy_hash(exp.exp) : exp
exp["result"] = self.evaluate(exp, obj, inputs)
operators = exp.keys
operators.each {|k|
if ["and", "or"].include?(k.to_s.downcase) # and/or atom is an array of atoms
exp[k].each {|atom|
self.evaluate_atoms(atom, obj, inputs)
}
elsif ["not", "!"].include?(k.to_s.downcase) # not atom is a hash expression
self.evaluate_atoms(exp[k], obj, inputs)
else
next
end
}
return exp
end
def self.subst(ruby_exp, obj, inputs)
Condition.subst(ruby_exp, obj, inputs)
end
def self.operands2humanvalue(ops, options={})
# puts "Enter: operands2humanvalue: ops: #{ops.inspect}"
ret = []
if ops["tag"]
v = nil
ret.push(ops["alias"] || self.value2human(ops["tag"], options))
MiqExpression.get_entry_details(ops["tag"]).each {|t|
v = "'" + t.first + "'" if t.last == ops["value"]
}
if ops["value"] == :user_input
v = "<user input>"
else
v ||= ops["value"].is_a?(String) ? "'" + ops["value"] + "'" : ops["value"]
end
ret.push(v)
elsif ops["field"]
ops["value"] ||= ''
if ops["field"] == "<count>"
ret.push(nil)
ret.push(ops["value"])
else
ret.push(ops["alias"] || self.value2human(ops["field"], options))
if ops["value"] == :user_input
ret.push("<user input>")
else
col_type = self.get_col_type(ops["field"]) || "string"
ret.push(self.quote_human(ops["value"], col_type.to_s))
end
end
elsif ops["count"]
ret.push("COUNT OF " + (ops["alias"] || self.value2human(ops["count"], options)).strip)
if ops["value"] == :user_input
ret.push("<user input>")
else
ret.push(ops["value"])
end
elsif ops["regkey"]
ops["value"] ||= ''
ret.push(ops["regkey"] + " : " + ops["regval"])
ret.push(ops["value"].is_a?(String) ? "'" + ops["value"] + "'" : ops["value"])
elsif ops["value"]
ret.push(nil)
ret.push(ops["value"])
end
return ret
end
def self.value2human(val, options={})
options = {
:include_model => true,
:include_table => true
}.merge(options)
@company ||= VMDB::Config.new("vmdb").config[:server][:company]
tables, col = val.split("-")
first = true
val_is_a_tag = false
ret = ""
if options[:include_table] == true
friendly = tables.split(".").collect {|t|
if t.downcase == "managed"
val_is_a_tag = true
@company + " Tags"
elsif t.downcase == "user_tag"
"My Tags"
else
if first
first = nil
next unless options[:include_model] == true
Dictionary.gettext(t, :type=>:model, :notfound=>:titleize)
else
Dictionary.gettext(t, :type=>:table, :notfound=>:titleize)
end
end
}.compact
ret = friendly.join(".")
ret << " : " unless ret.blank? || col.blank?
end
if val_is_a_tag
if col
classification = options[:classification] || Classification.find_by_name(col)
ret << (classification ? classification.description : col)
end
else
model = tables.blank? ? nil : tables.split(".").last.singularize.camelize
dict_col = model.nil? ? col : [model, col].join(".")
ret << Dictionary.gettext(dict_col, :type=>:column, :notfound=>:titleize) if col
end
ret = " #{ret}" unless ret.include?(":")
ret
end
def self.operands2sqlvalue(operator, ops)
# puts "Enter: operands2rubyvalue: operator: #{operator}, ops: #{ops.inspect}"
operator = operator.downcase
ret = []
if ops["field"]
ret << self.get_sqltable(ops["field"].split("-").first) + "." + ops["field"].split("-").last
col_type = self.get_col_type(ops["field"]) || "string"
if ["like", "not like", "starts with", "ends with", "includes"].include?(operator)
ret.push(ops["value"])
else
ret.push(self.quote(ops["value"], col_type.to_s, :sql))
end
elsif ops["count"]
val = self.get_sqltable(ops["count"].split("-").first) + "." + ops["count"].split("-").last
ret << "count(#{val})" #TODO
ret.push(ops["value"])
else
return nil
end
return ret
end
def self.operands2rubyvalue(operator, ops, context_type)
# puts "Enter: operands2rubyvalue: operator: #{operator}, ops: #{ops.inspect}"
operator = operator.downcase
ops["tag"] = ops["field"] if operator == "contains" and !ops["tag"] # process values in contains as tags
ret = []
if ops["tag"] && context_type != "hash"
ref, val = self.value2tag(self.preprocess_managed_tag(ops["tag"]), ops["value"])
fld = val
ret.push(ref ? "<exist ref=#{ref}>#{val}</exist>" : "<exist>#{val}</exist>")
elsif ops["tag"] && context_type == "hash"
# This is only for supporting reporting "display filters"
# In the report object the tag value is actually the description and not the raw tag name.
# So we have to trick it by replacing the value with the description.
description = MiqExpression.get_entry_details(ops["tag"]).inject("") {|s,t|
break(t.first) if t.last == ops["value"]
s
}
val = ops["tag"].split(".").last.split("-").join(".")
fld = "<value type=string>#{val}</value>"
ret.push(fld)
ret.push(self.quote(description, "string"))
elsif ops["field"]
if ops["field"] == "<count>"
ret.push("<count>")
ret.push(ops["value"])
else
case context_type
when "hash"
ref = nil
val = ops["field"].split(".").last.split("-").join(".")
else
ref, val = self.value2tag(ops["field"])
end
col_type = self.get_col_type(ops["field"]) || "string"
col_type = "raw" if operator == "ruby"
fld = val
fld = ref ? "<value ref=#{ref}, type=#{col_type}>#{val}</value>" : "<value type=#{col_type}>#{val}</value>"
ret.push(fld)
if ["like", "not like", "starts with", "ends with", "includes", "regular expression matches", "regular expression does not match", "ruby"].include?(operator)
ret.push(ops["value"])
else
ret.push(self.quote(ops["value"], col_type.to_s))
end
end
elsif ops["count"]
ref, count = self.value2tag(ops["count"])
ret.push(ref ? "<count ref=#{ref}>#{count}</count>" : "<count>#{count}</count>")
ret.push(ops["value"])
elsif ops["regkey"]
ret.push("<registry>#{ops["regkey"].strip} : #{ops["regval"]}</registry>")
if ["like", "not like", "starts with", "ends with", "includes", "regular expression matches", "regular expression does not match"].include?(operator)
ret.push(ops["value"])
elsif operator == "key exists"
ret = "<registry key_exists=1, type=boolean>#{ops["regkey"].strip}</registry> == 'true'"
elsif operator == "value exists"
ret = "<registry value_exists=1, type=boolean>#{ops["regkey"].strip} : #{ops["regval"]}</registry> == 'true'"
else
ret.push(self.quote(ops["value"], "string"))
end
end
return ret
end
def self.quote(val, typ, mode=:ruby)
case typ.to_s
when "string", "text", "boolean", nil
val = "" if val.nil? # treat nil value as empty string
return mode == :sql ? ActiveRecord::Base.connection.quote(val) : "'" + val.to_s.gsub(/'/, "\\\\'") + "'" # escape any embedded single quotes
when "date"
return "nil" if val.blank? # treat nil value as empty string
return mode == :sql ? ActiveRecord::Base.connection.quote(val) : "\'#{val}\'.to_date"
when "datetime"
return "nil" if val.blank? # treat nil value as empty string
return mode == :sql ? ActiveRecord::Base.connection.quote(val.iso8601) : "\'#{val.iso8601}\'.to_time"
when "integer", "decimal", "fixnum"
return val.to_s.to_i_with_method
when "float"
return val.to_s.to_f_with_method
when "numeric_set"
val = val.split(",") if val.kind_of?(String)
v_arr = val.to_miq_a.collect do |v|
v = eval(v) rescue nil if v.kind_of?(String)
v.kind_of?(Range) ? v.to_a : v
end.flatten.compact.uniq.sort
return "[#{v_arr.join(",")}]"
when "string_set"
val = val.split(",") if val.kind_of?(String)
v_arr = val.to_miq_a.collect { |v| "'#{v.to_s.strip}'" }.flatten.uniq.sort
return "[#{v_arr.join(",")}]"
when "raw"
return val
else
return val
end
end
def self.quote_human(val, typ)
case typ.to_s
when "integer", "decimal", "fixnum", "float"
return val.to_i unless val.to_s.number_with_method? || typ.to_s == "float"
if val =~ /^([0-9\.,]+)\.([a-z]+)$/
val = $1; sfx = $2
if sfx.ends_with?("bytes") && FORMAT_BYTE_SUFFIXES.has_key?(sfx.to_sym)
return "#{val} #{FORMAT_BYTE_SUFFIXES[sfx.to_sym]}"
else
return "#{val} #{sfx.titleize}"
end
else
return val
end
when "string", "date", "datetime"
return "\"#{val}\""
else
return self.quote(val, typ)
end
end
def self.re_escape(s)
Regexp.escape(s).gsub(/\//, '\/')
end
def self.preprocess_managed_tag(tag)
path, val = tag.split("-")
path_arr = path.split(".")
if path_arr.include?("managed") || path_arr.include?("user_tag")
name = nil
while path_arr.first != "managed" && path_arr.first != "user_tag" do
name = path_arr.shift
end
return [name].concat(path_arr).join(".") + "-" + val
end
return tag
end
def self.value2tag(tag, val=nil)
val = val.to_s.gsub(/\//, "%2f") unless val.nil? #encode embedded / characters in values since / is used as a tag seperator
v = tag.to_s.split(".").compact.join("/") #split model path and join with "/"
v = v.to_s.split("-").join("/") #split out column name and join with "/"
v = [v, val].join("/") #join with value
v_arr = v.split("/")
ref = v_arr.shift #strip off model (eg. VM)
v_arr[0] = "user" if v_arr.first == "user_tag"
v_arr.unshift("virtual") unless v_arr.first == "managed" || v_arr.first == "user" #add in tag designation
return [ref.downcase, "/" + v_arr.join("/")]
end
def self.normalize_ruby_operator(str)
str = str.upcase
case str
when "EQUAL", "="
"=="
when "NOT"
"!"
when "LIKE", "NOT LIKE", "STARTS WITH", "ENDS WITH", "INCLUDES", "REGULAR EXPRESSION MATCHES"
"=~"
when "REGULAR EXPRESSION DOES NOT MATCH"
"!~"
when "IS NULL", "IS EMPTY"
"=="
when "IS NOT NULL", "IS NOT EMPTY"
"!="
when "BEFORE"
"<"
when "AFTER"
">"
else
str.downcase
end
end
def self.normalize_sql_operator(str)
str = str.upcase
case str
when "EQUAL"
"="
when "!"
"NOT"
when "EXIST"
"CONTAINS"
when "LIKE", "NOT LIKE", "STARTS WITH", "ENDS WITH", "INCLUDES"
"LIKE"
when "IS EMPTY"
"="
when "IS NOT EMPTY"
"!="
when "BEFORE"
"<"
when "AFTER"
">"
else
str
end
end
def self.normalize_operator(str)
str = str.upcase
case str
when "EQUAL"
"="
when "!"
"NOT"
when "EXIST"
"CONTAINS"
else
str
end
end
def self.get_sqltable(path)
# puts "Enter: get_sqltable: path: #{path}"
parts = path.split(".")
name = parts.last
klass = parts.shift.constantize
parts.reverse.each do |assoc|
ref = klass.reflections[assoc.to_sym]
if ref.nil?
klass = nil
break
end
klass = ref.class_name.constantize
end
return klass ? klass.table_name : name.pluralize.underscore
end
def self.base_tables
@@base_tables
end
def self.model_details(model, opts = {:typ=>"all", :include_model=>true, :include_tags=>false, :include_my_tags=>false})
@classifications = nil
model = model.to_s
opts = {:typ=>"all", :include_model=>true}.merge(opts)
if opts[:typ] == "tag"
tags_for_model = self.tag_details(model, model, opts)
result = []
TAG_CLASSES.each_slice(2) {|tc, name|
next if tc.constantize.base_class == model.constantize.base_class
path = [model, name].join(".")
result.concat(self.tag_details(tc, path, opts))
}
@classifications = nil
return tags_for_model.concat(result.sort!{|a,b|a.to_s<=>b.to_s})
end
relats = self.get_relats(model)
result = []
unless opts[:typ] == "count" || opts[:typ] == "find"
result = self.get_column_details(relats[:columns], model, opts).sort!{|a,b|a.to_s<=>b.to_s}
result.concat(self.tag_details(model, model, opts)) if opts[:include_tags] == true
end
result.concat(self._model_details(relats, opts).sort!{|a,b|a.to_s<=>b.to_s})
@classifications = nil
return result
end
def self._model_details(relats, opts)
result = []
relats[:reflections].each {|assoc, ref|
case opts[:typ]
when "count"
result.push(self.get_table_details(ref[:parent][:path])) if ref[:parent][:multivalue]
when "find"
result.concat(self.get_column_details(ref[:columns], ref[:parent][:path], opts)) if ref[:parent][:multivalue]
else
result.concat(self.get_column_details(ref[:columns], ref[:parent][:path], opts))
result.concat(self.tag_details(ref[:parent][:assoc_class], ref[:parent][:path], opts)) if opts[:include_tags] == true
end
result.concat(self._model_details(ref, opts))
}
return result
end
def self.tag_details(model, path, opts)
return [] unless TAG_CLASSES.include?(model)
result = []
@classifications ||= self.get_categories
@classifications.each {|name,cat|
prefix = path.nil? ? "managed" : [path, "managed"].join(".")
field = prefix + "-" + name
result.push([self.value2human(field, opts.merge(:classification => cat)), field])
}
if opts[:include_my_tags] && opts[:userid] && Tag.exists?(["name like ?", "/user/#{opts[:userid]}/%"])
prefix = path.nil? ? "user_tag" : [path, "user_tag"].join(".")
field = prefix + "-" + opts[:userid]
result.push([self.value2human(field, opts), field])
end
result.sort!{|a,b|a.to_s<=>b.to_s}
end
def self.get_relats(model)
@model_relats ||= {}
@model_relats[model] ||= self.build_relats(model)
end
def self.build_lists(model)
$log.info("MIQ(MiqExpression-build_lists) Building lists for: [#{model}]...")
# Build expression lists
[:exp_available_fields, :exp_available_counts, :exp_available_finds].each {|what| self.miq_adv_search_lists(model, what)}
# Build reporting lists
self.reporting_available_fields(model) unless model == model.ends_with?("Trend") || model.ends_with?("Performance") # Can't do trend/perf models at startup
end
def self.miq_adv_search_lists(model, what)
@miq_adv_search_lists ||= {}
@miq_adv_search_lists[model.to_s] ||= {}
case what.to_sym
when :exp_available_fields then @miq_adv_search_lists[model.to_s][:exp_available_fields] ||= MiqExpression.model_details(model, :typ=>"field", :include_model=>true)
when :exp_available_counts then @miq_adv_search_lists[model.to_s][:exp_available_counts] ||= MiqExpression.model_details(model, :typ=>"count", :include_model=>true)
when :exp_available_finds then @miq_adv_search_lists[model.to_s][:exp_available_finds] ||= MiqExpression.model_details(model, :typ=>"find", :include_model=>true)
end
end
def self.reporting_available_fields(model, interval = nil)
@reporting_available_fields ||= {}
if model.to_s == "VimPerformanceTrend"
@reporting_available_fields[model.to_s] ||= {}
@reporting_available_fields[model.to_s][interval.to_s] ||= VimPerformanceTrend.trend_model_details(interval.to_s)
elsif model.ends_with?("Performance")
@reporting_available_fields[model.to_s] ||= {}
@reporting_available_fields[model.to_s][interval.to_s] ||= MiqExpression.model_details(model, :include_model => false, :include_tags => true, :interval =>interval)
elsif model.to_s == "Chargeback"
@reporting_available_fields[model.to_s] ||= MiqExpression.model_details(model, :include_model=>false, :include_tags=>true).select {|c| c.last.ends_with?("_cost") || c.last.ends_with?("_metric") || c.last.ends_with?("-owner_name")}
else
@reporting_available_fields[model.to_s] ||= MiqExpression.model_details(model, :include_model=>false, :include_tags=>true)
end
end
def self.build_relats(model, parent={}, seen=[])
$log.info("MIQ(MiqExpression.build_relats) Building relationship tree for: [#{parent[:path]} => #{model}]...")
model = model_class(model)
parent[:path] ||= model.name
parent[:root] ||= model.name
result = {:columns => model.column_names_with_virtual, :parent => parent}
result[:reflections] = {}
model.reflections_with_virtual.each do |assoc, ref|
next unless @@include_tables.include?(assoc.to_s.pluralize)
next if assoc.to_s.pluralize == "event_logs" && parent[:root] == "Host" && !@@proto
next if assoc.to_s.pluralize == "processes" && parent[:root] == "Host" # Process data not available yet for Host
next if ref.macro == :belongs_to && model.name != parent[:root]
assoc_class = ref.klass.name
new_parent = {
:macro => ref.macro,
:path => [parent[:path], determine_relat_path(ref)].join("."),
:assoc => assoc,
:assoc_class => assoc_class,
:root => parent[:root]
}
new_parent[:direction] = new_parent[:macro] == :belongs_to ? :up : :down
new_parent[:multivalue] = [:has_many, :has_and_belongs_to_many].include?(new_parent[:macro])
seen_key = [model.name, assoc].join("_")
unless seen.include?(seen_key) ||
assoc_class == parent[:root] ||
parent[:path].include?(assoc.to_s) ||
parent[:path].include?(assoc.to_s.singularize) ||
parent[:direction] == :up ||
parent[:multivalue]
seen.push(seen_key)
result[:reflections][assoc] = self.build_relats(assoc_class, new_parent, seen)
end
end
result
end
def self.get_table_details(table)
# puts "Enter: get_table_details: model: #{model}, parent: #{parent.inspect}"
[self.value2human(table), table]
end
def self.get_column_details(column_names, parent, opts)
include_model = opts[:include_model]
base_model = parent.split(".").first
excludes = EXCLUDE_COLUMNS
# special case for C&U ad-hoc reporting
if opts[:interval] && opts[:interval] != "daily" && base_model.ends_with?("Performance") && !parent.include?(".")
excludes += ["^min_.*$", "^max_.*$", "^.*derived_storage_.*$", "created_on"]
elsif opts[:interval] && base_model.ends_with?("Performance") && !parent.include?(".")
excludes += ["created_on"]
end
excludes += ["logical_cpus"] if parent == "Vm.hardware"
case base_model
when "VmPerformance"
excludes += ["^.*derived_host_count_off$", "^.*derived_host_count_on$", "^.*derived_vm_count_off$", "^.*derived_vm_count_on$", "^.*derived_storage.*$"]
when "HostPerformance"
excludes += ["^.*derived_host_count_off$", "^.*derived_host_count_on$", "^.*derived_storage.*$", "^abs_.*$"]
when "EmsClusterPerformance"
excludes += ["^.*derived_storage.*$", "sys_uptime_absolute_latest", "^abs_.*$"]
when "StoragePerformance"
includes = ["^.*derived_storage.*$", "^timestamp$", "v_date", "v_time", "resource_name"]
column_names = column_names.collect { |c|
next(c) if includes.include?(c)
c if includes.detect {|incl| c.match(incl) }
}.compact
end
column_names.collect {|c|
# check for direct match first
next if excludes.include?(c) && !EXCLUDE_EXCEPTIONS.include?(c)
# check for regexp match if no direct match
col = c
excludes.each {|excl|
if c.match(excl)
col = nil
break
end
} unless EXCLUDE_EXCEPTIONS.include?(c)
if col
field = parent + "-" + col
[self.value2human(field, :include_model => include_model), field]
end
}.compact
end
def self.get_col_type(field)
model, parts, col = self.parse_field(field)
return :string if model.downcase == "managed" || parts.last == "managed"
return nil unless field.include?("-")
model = self.determine_model(model, parts)
return nil if model.nil?
self.col_type(model, col)
end
def self.col_type(model, col)
model = model_class(model)
col = model.columns_hash_with_virtual[col.to_s]
return col.nil? ? nil : col.type
end
def self.parse_field(field)
col = field.split("-").last
col = col.split("__").first unless col.nil? # throw away pivot table suffix if it exists before looking up type
parts = field.split("-").first.split(".")
model = parts.shift
return model, parts, col
end
NUM_OPERATORS = ["=", "!=", "<", "<=", ">=", ">", "RUBY"]
STRING_OPERATORS = ["=",
"STARTS WITH",
"ENDS WITH",
"INCLUDES",
"IS NULL",
"IS NOT NULL",
"IS EMPTY",
"IS NOT EMPTY",
"REGULAR EXPRESSION MATCHES",
"REGULAR EXPRESSION DOES NOT MATCH",
"RUBY"]
SET_OPERATORS = ["INCLUDES ALL",
"INCLUDES ANY",
"LIMITED TO",
"RUBY"]
REGKEY_OPERATORS = ["KEY EXISTS",
"VALUE EXISTS"]
BOOLEAN_OPERATORS = ["=",
"IS NULL",
"IS NOT NULL"]
DATE_TIME_OPERATORS = ["IS", "BEFORE", "AFTER", "FROM", "IS EMPTY", "IS NOT EMPTY"]
def self.get_col_operators(field)
if field == :count || field == :regkey
col_type = field
else
col_type = self.get_col_type(field.to_s) || :string
end
case col_type.to_s.downcase.to_sym
when :string
return STRING_OPERATORS
when :integer, :float, :fixnum
return NUM_OPERATORS
when :count
return NUM_OPERATORS - ["RUBY"]
when :numeric_set, :string_set
return SET_OPERATORS
when :regkey
return STRING_OPERATORS + REGKEY_OPERATORS
when :boolean
return BOOLEAN_OPERATORS
when :date, :datetime
return DATE_TIME_OPERATORS
else
return STRING_OPERATORS
end
end
STYLE_OPERATORS_EXCLUDES = ["RUBY", "REGULAR EXPRESSION MATCHES", "REGULAR EXPRESSION DOES NOT MATCH", "FROM"]
def self.get_col_style_operators(field)
result = self.get_col_operators(field) - STYLE_OPERATORS_EXCLUDES
end
def self.get_entry_details(field)
ns = field.split("-").first.split(".").last
if ns == "managed"
cat = field.split("-").last
catobj = Classification.find_by_name(cat)
return catobj ? catobj.entries.collect {|e| [e.description, e.name]} : []
elsif ns == "user_tag" || ns == "user"
cat = field.split("-").last
return Tag.find(:all, :conditions => ["name like ?", "/user/#{cat}%"]).collect {|t| [t.name.split("/").last, t.name.split("/").last]}
else
return field
end
end
def self.is_plural?(field)
parts = field.split("-").first.split(".")
macro = nil
model = model_class(parts.shift)
parts.each do |assoc|
ref = model.reflections_with_virtual[assoc.to_sym]
return false if ref.nil?
macro = ref.macro
model = ref.klass
end
[:has_many, :has_and_belongs_to_many].include?(macro)
end
def self.atom_error(field, operator, value)
return false if operator == "DEFAULT" # No validation needed for style DEFAULT operator
value = value.to_s unless value.kind_of?(Array)
dt = case operator.to_s.downcase
when "ruby" # TODO
:ruby
when "regular expression matches", "regular expression does not match" #TODO
:regexp
else
if field == :count
:integer
else
col_info = self.get_col_info(field)
[:bytes, :megabytes].include?(col_info[:format_sub_type]) ? :integer : col_info[:data_type]
end
end
case dt
when :string, :text
return false
when :integer, :fixnum, :decimal, :float
return false if self.send((dt == :float ? :is_numeric? : :is_integer?), value)
dt_human = dt == :float ? "Number" : "Integer"
return "#{dt_human} value must not be blank" if value.gsub(/,/, "").blank?
if value.include?(".") && (value.split(".").last =~ /([a-z]+)/i)
sfx = $1
sfx = sfx.ends_with?("bytes") && FORMAT_BYTE_SUFFIXES.has_key?(sfx.to_sym) ? FORMAT_BYTE_SUFFIXES[sfx.to_sym] : sfx.titleize
value = "#{value.split(".")[0..-2].join(".")} #{sfx}"
end
return "Value '#{value}' is not a valid #{dt_human}"
when :date, :datetime
return false if operator.downcase.include?("empty")
values = value.to_miq_a
return "No Date/Time value specified" if values.empty? || values.include?(nil)
return "Two Date/Time values must be specified" if operator.downcase == "from" && values.length < 2
values_converted = values.collect do |v|
return "Date/Time value must not be blank" if value.blank?
v_cvt = self.normalize_date_time(v, "UTC") rescue nil
return "Value '#{v}' is not valid" if v_cvt.nil?
v_cvt
end
return "Invalid Date/Time range, #{values[1]} comes before #{values[0]}" if values_converted.length > 1 && values_converted[0] > values_converted[1]
return false
when :boolean
return "Value must be true or false" unless operator.downcase.include?("null") || ["true", "false"].include?(value)
return false
when :regexp
begin
Regexp.new(value).match("foo")
rescue => err
return "Regular expression '#{value}' is invalid, '#{err.message}'"
end
return false
when :ruby
return "Ruby Script must not be blank" if value.blank?
return false
else
return false
end
return "Value '#{value}' must be in the form of #{FORMAT_SUB_TYPES[dt][:short_name]}"
end
def self.get_categories
classifications = Classification.in_my_region.hash_all_by_type_and_name(:show => true)
categories_with_entries = classifications.reject { |k, v| !v.has_key?(:entry) }
categories_with_entries.each_with_object({}) do |(name, hash), categories|
categories[name] = hash[:category]
end
end
def self.model_class(model)
# TODO: the temporary cache should be removed after widget refactoring
@@model_class ||= Hash.new { |h, m| h[m] = m.is_a?(Class) ? m: m.to_s.singularize.camelize.constantize rescue nil }
@@model_class[model]
end
def self.is_integer?(n)
n = n.to_s
n2 = n.gsub(/,/, "") # strip out commas
begin
Integer n2
return true
rescue
return false unless n.number_with_method?
begin
n2 = n.to_f_with_method
return (n2.to_i == n2)
rescue
return false
end
end
end
def self.is_numeric?(n)
n = n.to_s
n2 = n.gsub(/,/, "") # strip out commas
begin
Float n2
return true
rescue
return false unless n.number_with_method?
begin
n.to_f_with_method
return true
rescue
return false
end
end
end
# Is an MiqExpression or an expression hash a quick_search
def self.quick_search?(exp)
return exp.quick_search? if exp.is_a?(self)
return self._quick_search?(exp)
end
def quick_search?
self.class._quick_search?(self.exp) # Pass the exp hash
end
# Is an expression hash a quick search?
def self._quick_search?(e)
if e.is_a?(Array)
e.each { |e_exp| return true if self._quick_search?(e_exp) }
elsif e.is_a?(Hash)
return true if e["value"] == :user_input
e.each_value {|e_exp| return true if self._quick_search?(e_exp)}
end
return false
end
private
def self.determine_model(model, parts)
model = model_class(model)
return nil if model.nil?
parts.each do |assoc|
ref = model.reflections_with_virtual[assoc.to_sym]
return nil if ref.nil?
model = ref.klass
end
model
end
def self.determine_relat_path(ref)
last_path = ref.name.to_s
class_from_association_name = model_class(last_path)
return last_path unless class_from_association_name
association_class = ref.klass
last_path = association_class.to_s.underscore if association_class < class_from_association_name
last_path
end
end #class MiqExpression
|
module ReportFormatter
class ReportHTML < Ruport::Formatter
renders :html, :for => ReportRenderer
def build_html_title
mri = options.mri
mri.html_title = String.new
mri.html_title << " <div style='height: 10px;'></div>"
mri.html_title << "<ul id='tab'>"
mri.html_title << "<li class='active'><a class='active'>"
mri.html_title << " #{mri.title}" unless mri.title.nil?
mri.html_title << "</a></li></ul>"
mri.html_title << '<div class="clr"></div><div class="clr"></div><div class="b"><div class="b"><div class="b"></div></div></div>'
mri.html_title << '<div id="element-box"><div class="t"><div class="t"><div class="t"></div></div></div><div class="m">'
end
def pad(str, len)
return "".ljust(len) if str.nil?
str = str.slice(0, len) # truncate long strings
str.ljust(len) # pad with whitespace
end
def build_document_header
build_html_title
end
def build_document_body
mri = options.mri
tz = mri.get_time_zone(Time.zone.name)
output << "<table class='style3'>"
output << "<thead>"
output << "<tr>"
# table heading
unless mri.headers.nil?
mri.headers.each do |h|
output << "<th class='title'>" << CGI.escapeHTML(h.to_s) << "</th>"
end
output << "</tr>"
output << "</thead>"
end
output << '<tbody>'
# table data
# save_val = nil
counter = 0
row = 0
unless mri.table.nil?
# Following line commented for now - for not showing repeating column values
# prev_data = String.new # Initialize the prev_data variable
tot_cpu = tot_ram = tot_space = tot_disk = tot_net = 0.0 if mri.db == "VimUsage" # Create usage total cols
cfg = VMDB::Config.new("vmdb").config[:reporting] # Read in the reporting column precisions
default_precision = cfg[:precision][:default] # Set the default
precision_by_column = cfg[:precision_by_column] # get the column overrides
precisions = {} # Hash to store columns we hit
# derive a default precision by looking at the suffixes of the column hearers
zero_precision_suffixes = ["(ms)", "(mb)", "(seconds)", "(b)"]
mri.headers.each_index do |i|
zero_precision_suffixes.each do |s|
if mri.headers[i].downcase.ends_with?(s) && precision_by_column[mri.col_order[i]].blank?
precisions[mri.col_order[i]] = 0
break
end
end
end
row_limit = mri.rpt_options && mri.rpt_options[:row_limit] ? mri.rpt_options[:row_limit] : 0
save_val = :_undefined_ # Hang on to the current group value
group_text = nil # Optionally override what gets displayed for the group (i.e. Chargeback)
use_table = mri.sub_table ? mri.sub_table : mri.table
use_table.data.each_with_index do |d, d_idx|
break if row_limit != 0 && d_idx > row_limit - 1
if ["y","c"].include?(mri.group) && mri.sortby != nil && save_val != d.data[mri.sortby[0]].to_s
unless d_idx == 0 # If not the first row, we are at a group break
output << group_rows(save_val, mri.col_order.length, group_text)
end
save_val = d.data[mri.sortby[0]].to_s
group_text = d.data["display_range"] if mri.db == "Chargeback" && mri.sortby[0] == "start_date" # Chargeback, sort by date, but show range
end
if row == 0
output << '<tr class="row0">'
row = 1
else
output << '<tr class="row1">'
row = 0
end
mri.col_formats ||= Array.new # Backward compat - create empty array for formats
mri.col_order.each_with_index do |c, c_idx|
if c == "resource_type" # Lookup models in resource_type col
output << '<td>'
output << ui_lookup(:model=>d.data[c])
output << "</td>"
elsif mri.db == "VimUsage" # Format usage columns
case c
when "cpu_usagemhz_rate_average"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c].to_f, :format=>:general_number_precision_1))
tot_cpu += d.data[c].to_f
when "derived_memory_used"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c].to_f, :format=>:megabytes_human))
tot_ram += d.data[c].to_f
when "derived_vm_used_disk_storage"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c], :format=>:bytes_human))
tot_space += d.data[c].to_f
when "derived_storage_used_managed"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c], :format=>:bytes_human))
tot_space += d.data[c].to_f
when "disk_usage_rate_average"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c].to_f, :format=>:general_number_precision_1)) <<
" (#{CGI.escapeHTML(mri.format(c, d.data[c].to_f*1.kilobyte*mri.extras[:interval], :format=>:bytes_human))})"
tot_disk += d.data[c].to_f
when "net_usage_rate_average"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c].to_f, :format=>:general_number_precision_1)) <<
" (#{CGI.escapeHTML(mri.format(c, d.data[c].to_f*1.kilobyte*mri.extras[:interval], :format=>:bytes_human))})"
tot_net += d.data[c].to_f
else
output << '<td>'
output << d.data[c].to_s
end
output << "</td>"
else
if d.data[c].is_a?(Time)
output << '<td style="text-align:center">'
elsif d.data[c].kind_of?(Bignum) || d.data[c].kind_of?(Fixnum) || d.data[c].kind_of?(Float)
output << '<td style="text-align:right">'
else
output << '<td>'
end
output << CGI.escapeHTML(mri.format(c.split("__").first,
d.data[c],
:format=>mri.col_formats[c_idx] ? mri.col_formats[c_idx] : :_default_,
:tz=>tz))
output << "</td>"
end
end
output << "</tr>"
end
if mri.db == "VimUsage" # Output usage totals
if row == 0
output << '<tr class="row0">'
row = 1
else
output << '<tr class="row1">'
row = 0
end
output << "<td><strong>Totals:</strong></td>"
mri.col_order.each do |c|
case c
when "cpu_usagemhz_rate_average"
output << '<td style="text-align:right"><strong>' <<
CGI.escapeHTML(mri.format(c, tot_cpu, :format=>:general_number_precision_1)) <<
"</strong></td>"
when "derived_memory_used"
output << '<td style="text-align:right"><strong>' <<
CGI.escapeHTML(mri.format(c, tot_ram, :format=>:megabytes_human)) <<
"</strong></td>"
when "derived_storage_used_managed"
output << '<td style="text-align:right"><strong>' <<
CGI.escapeHTML(mri.format(c, tot_space, :format=>:bytes_human)) <<
"</strong></td>"
when "derived_vm_used_disk_storage"
output << '<td style="text-align:right"><strong>' <<
CGI.escapeHTML(mri.format(c, tot_space, :format=>:bytes_human)) <<
"</strong></td>"
when "disk_usage_rate_average"
output << '<td style="text-align:right"><strong>' << CGI.escapeHTML(mri.format(c, tot_disk, :format=>:general_number_precision_1)) <<
" (#{CGI.escapeHTML(mri.format(c, tot_disk*1.kilobyte*mri.extras[:interval], :format=>:bytes_human))})" << "</strong></td>"
when "net_usage_rate_average"
output << '<td style="text-align:right"><strong>' << CGI.escapeHTML(mri.format(c, tot_net, :format=>:general_number_precision_1)) <<
" (#{CGI.escapeHTML(mri.format(c, tot_net*1.kilobyte*mri.extras[:interval], :format=>:bytes_human))})" << "</strong></td>"
end
end
output << "</tr>"
end
end
if ["y","c"].include?(mri.group) && mri.sortby != nil
output << group_rows(save_val, mri.col_order.length, group_text)
output << group_rows(:_total_, mri.col_order.length)
end
output << '</tbody>'
end
# Generate grouping rows for the passed in grouping value
def group_rows(group, col_count, group_text = nil)
mri = options.mri
grp_output = ""
if mri.extras[:grouping] && mri.extras[:grouping][group] # See if group key exists
if mri.group == "c" # Show counts row
if group == :_total_
grp_output << "<tr><td class='group' colspan='#{col_count}'>Count for All Rows: #{mri.extras[:grouping][group][:count]}</td></tr>"
else
g = group_text ? group_text : group
grp_output << "<tr><td class='group' colspan='#{col_count}'>Count for #{g.blank? ? "<blank>" : g}: #{mri.extras[:grouping][group][:count]}</td></tr>"
end
else
if group == :_total_
grp_output << "<tr><td class='group' colspan='#{col_count}'>All Rows</td></tr>"
else
g = group_text ? group_text : group
grp_output << "<tr><td class='group' colspan='#{col_count}'>#{g.blank? ? "<blank>" : g} </td></tr>"
end
end
MiqReport::GROUPINGS.each do |calc| # Add an output row for each group calculation
if mri.extras[:grouping][group].has_key?(calc.first) # Only add a row if there are calcs of this type for this group value
grp_output << "<tr>"
grp_output << "<td class='group'>#{calc.last.pluralize}:</td>"
mri.col_order.each_with_index do |c, c_idx| # Go through the columns
next if c_idx == 0 # Skip first column
grp_output << "<td class='group' style='text-align:right'>"
grp_output << CGI.escapeHTML(mri.format(c.split("__").first,
mri.extras[:grouping][group][calc.first][c],
:format=>mri.col_formats[c_idx] ? mri.col_formats[c_idx] : :_default_
)
) if mri.extras[:grouping][group].has_key?(calc.first)
grp_output << "</td>"
end
grp_output << "</tr>"
end
end
end
grp_output << "<tr><td class='group' colspan='#{col_count}'> </td></tr>" unless group == :_total_
return grp_output
end
def build_document_footer
mri = options.mri
output << "<tfoot>"
output << "<td colspan='15'>"
output << "<del class='container'>"
# output << "<div class='pagination'>"
# output << '<div class="limit">Display #<select name="limit" id="limit" class="inputbox" size="1" onchange="submitform();"><option value="5" >5</option><option value="10" >10</option><option value="15" >15</option><option value="20" selected="selected">20</option><option value="25" >25</option><option value="30" >30</option><option value="50" >50</option><option value="100" >100</option><option value="0" >all</option></select></div>'
# output << '<div class="button2-right off"><div class="start"><span>Start</span></div></div><div class="button2-right off"><div class="prev"><span>Prev</span></div></div>'
# output << ""
# output << ""
# output << "<div class='button2-left'><div class='page'>"
# output << "<a title='1' onclick='javascript: document.adminForm.limitstart.value=0; submitform();return false;'>1</a>"
# output << "<a title='2' onclick='javascript: document.adminForm.limitstart.value=20; submitform();return false;'>2</a>"
# output << "</div></div>"
# output << "<div class='button2-left'><div class='next'>"
# output << "<a title='Next' onclick='javascript: document.adminForm.limitstart.value=20; submitform();return false;'>Next</a>"
# output << "</div></div>"
# output << '<div class="button2-left"><div class="end"><a title="End" onclick="javascript: document.adminForm.limitstart.value=40; submitform();return false;">End</a></div></div>'
# output << "<div class='limit'>page 1 of 3</div><input type='hidden' name='limitstart' value='0' /></div>"
output << "</del>"
output << "</td>"
output << "</tfoot>"
output << "</table>"
if mri.filter_summary
output << "#{mri.filter_summary}"
end
# output << "<div class='clr'></div>"
# output << "</div>"
# output << "<div class='b'>"
# output << "<div class='b'>"
# output << "<div class='b'></div>"
# output << "</div>"
# output << "</div>"
# output << "</div>"
end
def finalize_document
output
end
end
end
Cap & U table styling fix
added no-hover class to Cap & U tables, removed fieldsets
https://bugzilla.redhat.com/show_bug.cgi?id=1135659
(transferred from ManageIQ/manageiq@f63f62a9c4e99a02ae9092c9d0a9e047fb025e0c)
module ReportFormatter
class ReportHTML < Ruport::Formatter
renders :html, :for => ReportRenderer
def build_html_title
mri = options.mri
mri.html_title = String.new
mri.html_title << " <div style='height: 10px;'></div>"
mri.html_title << "<ul id='tab'>"
mri.html_title << "<li class='active'><a class='active'>"
mri.html_title << " #{mri.title}" unless mri.title.nil?
mri.html_title << "</a></li></ul>"
mri.html_title << '<div class="clr"></div><div class="clr"></div><div class="b"><div class="b"><div class="b"></div></div></div>'
mri.html_title << '<div id="element-box"><div class="t"><div class="t"><div class="t"></div></div></div><div class="m">'
end
def pad(str, len)
return "".ljust(len) if str.nil?
str = str.slice(0, len) # truncate long strings
str.ljust(len) # pad with whitespace
end
def build_document_header
build_html_title
end
def build_document_body
mri = options.mri
tz = mri.get_time_zone(Time.zone.name)
output << "<table class='style3'>"
output << "<thead>"
output << "<tr>"
# table heading
unless mri.headers.nil?
mri.headers.each do |h|
output << "<th class='title'>" << CGI.escapeHTML(h.to_s) << "</th>"
end
output << "</tr>"
output << "</thead>"
end
output << '<tbody>'
# table data
# save_val = nil
counter = 0
row = 0
unless mri.table.nil?
# Following line commented for now - for not showing repeating column values
# prev_data = String.new # Initialize the prev_data variable
tot_cpu = tot_ram = tot_space = tot_disk = tot_net = 0.0 if mri.db == "VimUsage" # Create usage total cols
cfg = VMDB::Config.new("vmdb").config[:reporting] # Read in the reporting column precisions
default_precision = cfg[:precision][:default] # Set the default
precision_by_column = cfg[:precision_by_column] # get the column overrides
precisions = {} # Hash to store columns we hit
# derive a default precision by looking at the suffixes of the column hearers
zero_precision_suffixes = ["(ms)", "(mb)", "(seconds)", "(b)"]
mri.headers.each_index do |i|
zero_precision_suffixes.each do |s|
if mri.headers[i].downcase.ends_with?(s) && precision_by_column[mri.col_order[i]].blank?
precisions[mri.col_order[i]] = 0
break
end
end
end
row_limit = mri.rpt_options && mri.rpt_options[:row_limit] ? mri.rpt_options[:row_limit] : 0
save_val = :_undefined_ # Hang on to the current group value
group_text = nil # Optionally override what gets displayed for the group (i.e. Chargeback)
use_table = mri.sub_table ? mri.sub_table : mri.table
use_table.data.each_with_index do |d, d_idx|
break if row_limit != 0 && d_idx > row_limit - 1
if ["y","c"].include?(mri.group) && mri.sortby != nil && save_val != d.data[mri.sortby[0]].to_s
unless d_idx == 0 # If not the first row, we are at a group break
output << group_rows(save_val, mri.col_order.length, group_text)
end
save_val = d.data[mri.sortby[0]].to_s
group_text = d.data["display_range"] if mri.db == "Chargeback" && mri.sortby[0] == "start_date" # Chargeback, sort by date, but show range
end
if row == 0
output << '<tr class="row0 no-hover">'
row = 1
else
output << '<tr class="row1 no-hover">'
row = 0
end
mri.col_formats ||= Array.new # Backward compat - create empty array for formats
mri.col_order.each_with_index do |c, c_idx|
if c == "resource_type" # Lookup models in resource_type col
output << '<td>'
output << ui_lookup(:model=>d.data[c])
output << "</td>"
elsif mri.db == "VimUsage" # Format usage columns
case c
when "cpu_usagemhz_rate_average"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c].to_f, :format=>:general_number_precision_1))
tot_cpu += d.data[c].to_f
when "derived_memory_used"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c].to_f, :format=>:megabytes_human))
tot_ram += d.data[c].to_f
when "derived_vm_used_disk_storage"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c], :format=>:bytes_human))
tot_space += d.data[c].to_f
when "derived_storage_used_managed"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c], :format=>:bytes_human))
tot_space += d.data[c].to_f
when "disk_usage_rate_average"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c].to_f, :format=>:general_number_precision_1)) <<
" (#{CGI.escapeHTML(mri.format(c, d.data[c].to_f*1.kilobyte*mri.extras[:interval], :format=>:bytes_human))})"
tot_disk += d.data[c].to_f
when "net_usage_rate_average"
output << '<td style="text-align:right">'
output << CGI.escapeHTML(mri.format(c, d.data[c].to_f, :format=>:general_number_precision_1)) <<
" (#{CGI.escapeHTML(mri.format(c, d.data[c].to_f*1.kilobyte*mri.extras[:interval], :format=>:bytes_human))})"
tot_net += d.data[c].to_f
else
output << '<td>'
output << d.data[c].to_s
end
output << "</td>"
else
if d.data[c].is_a?(Time)
output << '<td style="text-align:center">'
elsif d.data[c].kind_of?(Bignum) || d.data[c].kind_of?(Fixnum) || d.data[c].kind_of?(Float)
output << '<td style="text-align:right">'
else
output << '<td>'
end
output << CGI.escapeHTML(mri.format(c.split("__").first,
d.data[c],
:format=>mri.col_formats[c_idx] ? mri.col_formats[c_idx] : :_default_,
:tz=>tz))
output << "</td>"
end
end
output << "</tr>"
end
if mri.db == "VimUsage" # Output usage totals
if row == 0
output << '<tr class="row0 no-hover">'
row = 1
else
output << '<tr class="row1 no-hover">'
row = 0
end
output << "<td><strong>Totals:</strong></td>"
mri.col_order.each do |c|
case c
when "cpu_usagemhz_rate_average"
output << '<td style="text-align:right"><strong>' <<
CGI.escapeHTML(mri.format(c, tot_cpu, :format=>:general_number_precision_1)) <<
"</strong></td>"
when "derived_memory_used"
output << '<td style="text-align:right"><strong>' <<
CGI.escapeHTML(mri.format(c, tot_ram, :format=>:megabytes_human)) <<
"</strong></td>"
when "derived_storage_used_managed"
output << '<td style="text-align:right"><strong>' <<
CGI.escapeHTML(mri.format(c, tot_space, :format=>:bytes_human)) <<
"</strong></td>"
when "derived_vm_used_disk_storage"
output << '<td style="text-align:right"><strong>' <<
CGI.escapeHTML(mri.format(c, tot_space, :format=>:bytes_human)) <<
"</strong></td>"
when "disk_usage_rate_average"
output << '<td style="text-align:right"><strong>' << CGI.escapeHTML(mri.format(c, tot_disk, :format=>:general_number_precision_1)) <<
" (#{CGI.escapeHTML(mri.format(c, tot_disk*1.kilobyte*mri.extras[:interval], :format=>:bytes_human))})" << "</strong></td>"
when "net_usage_rate_average"
output << '<td style="text-align:right"><strong>' << CGI.escapeHTML(mri.format(c, tot_net, :format=>:general_number_precision_1)) <<
" (#{CGI.escapeHTML(mri.format(c, tot_net*1.kilobyte*mri.extras[:interval], :format=>:bytes_human))})" << "</strong></td>"
end
end
output << "</tr>"
end
end
if ["y","c"].include?(mri.group) && mri.sortby != nil
output << group_rows(save_val, mri.col_order.length, group_text)
output << group_rows(:_total_, mri.col_order.length)
end
output << '</tbody>'
end
# Generate grouping rows for the passed in grouping value
def group_rows(group, col_count, group_text = nil)
mri = options.mri
grp_output = ""
if mri.extras[:grouping] && mri.extras[:grouping][group] # See if group key exists
if mri.group == "c" # Show counts row
if group == :_total_
grp_output << "<tr><td class='group' colspan='#{col_count}'>Count for All Rows: #{mri.extras[:grouping][group][:count]}</td></tr>"
else
g = group_text ? group_text : group
grp_output << "<tr><td class='group' colspan='#{col_count}'>Count for #{g.blank? ? "<blank>" : g}: #{mri.extras[:grouping][group][:count]}</td></tr>"
end
else
if group == :_total_
grp_output << "<tr><td class='group' colspan='#{col_count}'>All Rows</td></tr>"
else
g = group_text ? group_text : group
grp_output << "<tr><td class='group' colspan='#{col_count}'>#{g.blank? ? "<blank>" : g} </td></tr>"
end
end
MiqReport::GROUPINGS.each do |calc| # Add an output row for each group calculation
if mri.extras[:grouping][group].has_key?(calc.first) # Only add a row if there are calcs of this type for this group value
grp_output << "<tr>"
grp_output << "<td class='group'>#{calc.last.pluralize}:</td>"
mri.col_order.each_with_index do |c, c_idx| # Go through the columns
next if c_idx == 0 # Skip first column
grp_output << "<td class='group' style='text-align:right'>"
grp_output << CGI.escapeHTML(mri.format(c.split("__").first,
mri.extras[:grouping][group][calc.first][c],
:format=>mri.col_formats[c_idx] ? mri.col_formats[c_idx] : :_default_
)
) if mri.extras[:grouping][group].has_key?(calc.first)
grp_output << "</td>"
end
grp_output << "</tr>"
end
end
end
grp_output << "<tr><td class='group' colspan='#{col_count}'> </td></tr>" unless group == :_total_
return grp_output
end
def build_document_footer
mri = options.mri
output << "<tfoot>"
output << "<td colspan='15'>"
output << "<del class='container'>"
# output << "<div class='pagination'>"
# output << '<div class="limit">Display #<select name="limit" id="limit" class="inputbox" size="1" onchange="submitform();"><option value="5" >5</option><option value="10" >10</option><option value="15" >15</option><option value="20" selected="selected">20</option><option value="25" >25</option><option value="30" >30</option><option value="50" >50</option><option value="100" >100</option><option value="0" >all</option></select></div>'
# output << '<div class="button2-right off"><div class="start"><span>Start</span></div></div><div class="button2-right off"><div class="prev"><span>Prev</span></div></div>'
# output << ""
# output << ""
# output << "<div class='button2-left'><div class='page'>"
# output << "<a title='1' onclick='javascript: document.adminForm.limitstart.value=0; submitform();return false;'>1</a>"
# output << "<a title='2' onclick='javascript: document.adminForm.limitstart.value=20; submitform();return false;'>2</a>"
# output << "</div></div>"
# output << "<div class='button2-left'><div class='next'>"
# output << "<a title='Next' onclick='javascript: document.adminForm.limitstart.value=20; submitform();return false;'>Next</a>"
# output << "</div></div>"
# output << '<div class="button2-left"><div class="end"><a title="End" onclick="javascript: document.adminForm.limitstart.value=40; submitform();return false;">End</a></div></div>'
# output << "<div class='limit'>page 1 of 3</div><input type='hidden' name='limitstart' value='0' /></div>"
output << "</del>"
output << "</td>"
output << "</tfoot>"
output << "</table>"
if mri.filter_summary
output << "#{mri.filter_summary}"
end
# output << "<div class='clr'></div>"
# output << "</div>"
# output << "<div class='b'>"
# output << "<div class='b'>"
# output << "<div class='b'></div>"
# output << "</div>"
# output << "</div>"
# output << "</div>"
end
def finalize_document
output
end
end
end
|
[Update] RSDTesting (0.1.11)
#
# Be sure to run `pod lib lint RSDTesting.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "RSDTesting"
s.version = "0.1.11"
s.summary = "Helper code for tests written in Swift."
s.description = <<-DESC
Testing helpers for asynchronous code, faking, mocking, and swizzling
DESC
s.homepage = "https://github.com/RaviDesai/RSDTesting"
s.license = 'MIT'
s.author = { "RaviDesai" => "ravidesai@me.com" }
s.source = { :git => "https://github.com/RaviDesai/RSDTesting.git", :tag => s.version.to_s }
s.platform = :ios, '9.0'
s.requires_arc = true
s.source_files = 'Pod/Classes/**/*'
# s.resource_bundles = {
# 'RSDTesting' => ['Pod/Assets/*.png']
# }
s.frameworks = 'UIKit', 'XCTest'
s.pod_target_xcconfig = { 'ENABLE_BITCODE' => 'NO' }
end
|
Updating podspec
Pod::Spec.new do |s|
s.name = 'CYRKeyboardButton'
s.version = '0.5.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A drop-in keyboard button that mimics the look, feel, and functionality of the native iOS keyboard buttons.'
s.author = { 'Illya Busigin' => 'http://illyabusigin.com/' }
s.source = { :git => 'https://github.com/illyabusigin/CYRKeyboardButton.git', :tag => '0.5.0' }
s.homepage = 'https://github.com/illyabusigin/CYRKeyboardButton'
s.platform = :ios
s.source_files = 'CYRKeyboardButton'
s.requires_arc = true
s.ios.deployment_target = '7.0'
s.dependency 'TurtleBezierPath'
end |
class InitializerGenerator < Rails::Generators::NamedBase
source_root File.expand_path("../templates", __FILE__)
gem 'mongoid', :git => "https://github.com/mongoid/mongoid.git"
gem 'bson_ext'
gem 'simple_form'
gem 'jquery-rails', '>= 0.2.6'
gem 'delayed_job', '>= 2.1.4', :git => "https://github.com/collectiveidea/delayed_job"
gem 'delayed_job_mongoid', :git => "https://github.com/collectiveidea/delayed_job_mongoid.git"
gem 'djinn'
def copy_initializer_file
copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
copy_file "script/tweet_engine_runner", "script/#{file_name}"
copy_file "config/tweet_engine.yml", "config/#{file_name}.yml"
end
end
Reverted as did not resolve issue
class InitializerGenerator < Rails::Generators::NamedBase
source_root File.expand_path("../templates", __FILE__)
def copy_initializer_file
copy_file "initializer.rb", "config/initializers/#{file_name}.rb"
copy_file "script/tweet_engine_runner", "script/#{file_name}"
copy_file "config/tweet_engine.yml", "config/#{file_name}.yml"
end
end |
module GirFFI
module Builders
# Class representing the argument and return value builders for a callback
# mapping function or marshaller. Implements collecting the conversion code
# and parameter and variable names for use by function builders.
class ArgumentBuilderCollection
attr_reader :return_value_builder
def initialize(return_value_builder, argument_builders, options = {})
@receiver_builder = options[:receiver_builder]
@error_argument_builder = options[:error_argument_builder]
@base_argument_builders = argument_builders
@return_value_builder = return_value_builder
set_up_argument_relations
end
def parameter_preparation
builders_for_pre_conversion.map(&:pre_conversion).flatten
end
def return_value_conversion
builders_for_post_conversion.map(&:post_conversion).flatten
end
def capture_variable_names
@capture_variable_names ||=
all_builders.map(&:capture_variable_name).compact
end
def call_argument_names
@call_argument_names ||= argument_builders.map(&:call_argument_name).compact
end
def method_argument_names
@method_argument_names ||= argument_builders.map(&:method_argument_name).compact
end
def return_value_name
# FIXME: Is if needed?
return_value_builder.return_value_name if return_value_builder.relevant?
end
def return_value_names
@return_value_names ||= all_builders.map(&:return_value_name).compact
end
def has_return_values?
return_value_names.any?
end
private
def argument_builders
@argument_builders ||= @base_argument_builders.dup.tap do |builders|
builders.unshift @receiver_builder if @receiver_builder
builders.push @error_argument_builder if @error_argument_builder
end
end
def set_up_argument_relations
@base_argument_builders.each do |bldr|
if (idx = bldr.closure) >= 0
@base_argument_builders[idx].closure = true
end
end
all_builders.each do |bldr|
if (idx = bldr.array_length_idx) >= 0
other = @base_argument_builders[idx]
next unless other
bldr.length_arg = other
other.array_arg = bldr
end
end
end
def all_builders
@all_builders ||= [return_value_builder] + argument_builders
end
def builders_for_pre_conversion
@builders_for_pre_conversion ||=
sorted_base_argument_builders.dup.tap do |builders|
builders.unshift @receiver_builder if @receiver_builder
builders.push @error_argument_builder if @error_argument_builder
end
end
def builders_for_post_conversion
@builders_for_post_conversion ||=
sorted_base_argument_builders.dup.tap do |builders|
builders.unshift @receiver_builder if @receiver_builder
builders.unshift @error_argument_builder if @error_argument_builder
builders.push return_value_builder
end
end
def sorted_base_argument_builders
@sorted_base_argument_builders ||= @base_argument_builders.
sort_by.with_index { |arg, i| [arg.array_length_idx, i] }
end
end
end
end
Remove useless conditional
module GirFFI
module Builders
# Class representing the argument and return value builders for a callback
# mapping function or marshaller. Implements collecting the conversion code
# and parameter and variable names for use by function builders.
class ArgumentBuilderCollection
attr_reader :return_value_builder
def initialize(return_value_builder, argument_builders, options = {})
@receiver_builder = options[:receiver_builder]
@error_argument_builder = options[:error_argument_builder]
@base_argument_builders = argument_builders
@return_value_builder = return_value_builder
set_up_argument_relations
end
def parameter_preparation
builders_for_pre_conversion.map(&:pre_conversion).flatten
end
def return_value_conversion
builders_for_post_conversion.map(&:post_conversion).flatten
end
def capture_variable_names
@capture_variable_names ||=
all_builders.map(&:capture_variable_name).compact
end
def call_argument_names
@call_argument_names ||= argument_builders.map(&:call_argument_name).compact
end
def method_argument_names
@method_argument_names ||= argument_builders.map(&:method_argument_name).compact
end
def return_value_name
return_value_builder.return_value_name
end
def return_value_names
@return_value_names ||= all_builders.map(&:return_value_name).compact
end
def has_return_values?
return_value_names.any?
end
private
def argument_builders
@argument_builders ||= @base_argument_builders.dup.tap do |builders|
builders.unshift @receiver_builder if @receiver_builder
builders.push @error_argument_builder if @error_argument_builder
end
end
def set_up_argument_relations
@base_argument_builders.each do |bldr|
if (idx = bldr.closure) >= 0
@base_argument_builders[idx].closure = true
end
end
all_builders.each do |bldr|
if (idx = bldr.array_length_idx) >= 0
other = @base_argument_builders[idx]
next unless other
bldr.length_arg = other
other.array_arg = bldr
end
end
end
def all_builders
@all_builders ||= [return_value_builder] + argument_builders
end
def builders_for_pre_conversion
@builders_for_pre_conversion ||=
sorted_base_argument_builders.dup.tap do |builders|
builders.unshift @receiver_builder if @receiver_builder
builders.push @error_argument_builder if @error_argument_builder
end
end
def builders_for_post_conversion
@builders_for_post_conversion ||=
sorted_base_argument_builders.dup.tap do |builders|
builders.unshift @receiver_builder if @receiver_builder
builders.unshift @error_argument_builder if @error_argument_builder
builders.push return_value_builder
end
end
def sorted_base_argument_builders
@sorted_base_argument_builders ||= @base_argument_builders.
sort_by.with_index { |arg, i| [arg.array_length_idx, i] }
end
end
end
end
|
module HealthDataStandards
module CQM
class QueryCache
include Mongoid::Document
include Mongoid::Timestamps
store_in collection: 'query_cache'
field :calculation_date, type: Time
field :status, type: Hash
field :measure_id, type: String
field :sub_id, type: String
field :population_ids, type: Hash
field :effective_date, type: Integer
field :IPP, type: Integer
field :DENOM, type: Integer
field :NUMER, type: Integer
field :antinumerator, type: Integer
field :DENEX, type: Integer
field :DENEXCEP, type: Integer
field :MSRPOPL, type: Integer
field :OBSERV, type: Float
field :supplemental_data, type: Hash
def self.aggregate_measure(measure_id, effective_date, filter=nil, test_id=nil)
cache_entries = self.where(effective_date: effective_date, measure_id: measure_id, test_id: test_id, filter: filter)
aggregate_count = AggregateCount.new(measure_id)
cache_entries.each do |cache_entry|
aggregate_count.add_entry(cache_entry)
end
aggregate_count
end
def is_stratification?
population_ids.has_key?('stratification')
end
def is_cv?
population_ids.has_key?('MSRPOPL')
end
end
end
end
Fixes handling of filters in the query cache
Previously, this code was adding a 'filter' attribute to the query.
The query_cache actually has a property called 'filters'.
Additionally, this now merges in the filters to allow for properties
such as 'filters.provider_id'.
module HealthDataStandards
module CQM
class QueryCache
include Mongoid::Document
include Mongoid::Timestamps
store_in collection: 'query_cache'
field :calculation_date, type: Time
field :status, type: Hash
field :measure_id, type: String
field :sub_id, type: String
field :population_ids, type: Hash
field :effective_date, type: Integer
field :IPP, type: Integer
field :DENOM, type: Integer
field :NUMER, type: Integer
field :antinumerator, type: Integer
field :DENEX, type: Integer
field :DENEXCEP, type: Integer
field :MSRPOPL, type: Integer
field :OBSERV, type: Float
field :supplemental_data, type: Hash
def self.aggregate_measure(measure_id, effective_date, filters=nil, test_id=nil)
query_hash = {'effective_date' => effective_date, 'measure_id' => measure_id,
'test_id' => test_id}
if filters
query_hash.merge!(filters)
end
cache_entries = self.where(query_hash)
aggregate_count = AggregateCount.new(measure_id)
cache_entries.each do |cache_entry|
aggregate_count.add_entry(cache_entry)
end
aggregate_count
end
def is_stratification?
population_ids.has_key?('stratification')
end
def is_cv?
population_ids.has_key?('MSRPOPL')
end
end
end
end
|
require "active_support"
require "active_record"
require "interest/utils"
require "interest/definition"
require "interest/follow_requestable/exceptions"
require "interest/follow_requestable/follow_requestee"
module Interest
module FollowRequestable
module FollowRequester
extend ActiveSupport::Concern
include Interest::Definition.instance_methods_for(:follow_requester, :follow_requestee)
def required_request_to_follow?(requestee)
requestee.follow_requestee? and requestee.requires_request_to_follow?(self)
end
def request_to_follow(requestee)
return nil unless valid_follow_request_for?(requestee)
begin
follow_requester_collection_for(requestee) << requestee
rescue ActiveRecord::RecordNotUnique
end
outgoing_follow_requests.find_by(requestee: requestee)
end
def request_to_follow!(requestee)
request_to_follow requestee or raise Interest::FollowRequestable::Rejected
end
def cancel_request_to_follow(requestee)
follow_requester_collection_for(requestee).delete requestee
end
def has_requested_to_follow?(requestee)
follow_requester_collection_for(requestee).include? requestee
end
def valid_follow_request_for?(requestee)
not (self == requestee or not follow_requestable?(requestee) or (follower? and following? requestee))
end
def follow_or_request_to_follow!(other)
if required_request_to_follow? other
returned = request_to_follow! other
which = :request_to_follow
else
returned = follow! other
which = :follow
end
FollowOrRequestToFollow.new which, returned, other
end
class FollowOrRequestToFollow < Struct.new(:which, :returned, :target)
def followed?
which == :follow
end
def requested_to_follow?
which == :request_to_follow
end
end
module ClassMethods
include Interest::Definition.class_methods_for(:follow_requester, :follow_requestee)
def define_follow_requester_association_methods
has_many :outgoing_follow_requests,
-> { uniq },
as: :requester,
dependent: :destroy,
class_name: "FollowRequest"
end
def define_follow_requester_association_method(source_type)
association_method_name = follow_requester_association_method_name_for source_type
has_many association_method_name,
-> { uniq },
through: :outgoing_follow_requests,
source: :requestee,
source_type: source_type
end
end
end
end
end
Refactor request_to_follow
require "active_support"
require "active_record"
require "interest/utils"
require "interest/definition"
require "interest/follow_requestable/exceptions"
require "interest/follow_requestable/follow_requestee"
module Interest
module FollowRequestable
module FollowRequester
extend ActiveSupport::Concern
include Interest::Definition.instance_methods_for(:follow_requester, :follow_requestee)
def required_request_to_follow?(requestee)
requestee.follow_requestee? and requestee.requires_request_to_follow?(self)
end
def request_to_follow(requestee)
return nil unless valid_follow_request_for?(requestee)
begin
outgoing_follow_requests.create!(requestee: requestee)
rescue ActiveRecord::RecordNotUnique
outgoing_follow_requests.find_by(requestee: requestee)
end
end
def request_to_follow!(requestee)
request_to_follow requestee or raise Interest::FollowRequestable::Rejected
end
def cancel_request_to_follow(requestee)
follow_requester_collection_for(requestee).delete requestee
end
def has_requested_to_follow?(requestee)
follow_requester_collection_for(requestee).include? requestee
end
def valid_follow_request_for?(requestee)
not (self == requestee or not follow_requestable?(requestee) or (follower? and following? requestee))
end
def follow_or_request_to_follow!(other)
if required_request_to_follow? other
returned = request_to_follow! other
which = :request_to_follow
else
returned = follow! other
which = :follow
end
FollowOrRequestToFollow.new which, returned, other
end
class FollowOrRequestToFollow < Struct.new(:which, :returned, :target)
def followed?
which == :follow
end
def requested_to_follow?
which == :request_to_follow
end
end
module ClassMethods
include Interest::Definition.class_methods_for(:follow_requester, :follow_requestee)
def define_follow_requester_association_methods
has_many :outgoing_follow_requests,
-> { uniq },
as: :requester,
dependent: :destroy,
class_name: "FollowRequest"
end
def define_follow_requester_association_method(source_type)
association_method_name = follow_requester_association_method_name_for source_type
has_many association_method_name,
-> { uniq },
through: :outgoing_follow_requests,
source: :requestee,
source_type: source_type
end
end
end
end
end
|
module Morpher
class Evaluator
class Transformer
# Too complex hash transformation evaluator
#
# FIXME: Shold be broken up in better primitives a decompose, compose pair
#
# @api private
#
class HashTransform < self
include Concord.new(:body)
register :hash_transform
# Test if evaluator is transitive
#
# FIXME: Needs to be calculated dynamically
#
# @return [true]
# if evaluator is transitive
#
# @return [false]
# otherwise
#
# @api private
#
def transitive?
body.all? do |evaluator|
self.class.is_transitive_keypair?(evaluator)
end
end
# Test if evaluator is a keypair
#
# FIXME:
# This is a side effect from this class is generally to big in sense of SRP.
# Must be refactorable away. But dunno now. Still exploring.
#
# @param [Evaluator]
#
# @api private
#
def self.is_transitive_keypair?(evaluator)
return false unless evaluator.kind_of?(Block)
body = evaluator.body
return false unless body.length == 3
fetch, operator, dump = body
fetch.kind_of?(Key::Fetch) && dump.kind_of?(Key::Dump) && operator.transitive?
end
# Call evaluator
#
# @param [Object] input
#
# @return [Object]
#
# @api private
#
def call(input)
content = body.map do |node|
node.call(input)
end
Hash[content]
end
# Return inverse evaluator
#
# @return [HashTransform]
#
# @api private
#
def inverse
inverse_body = body.map do |evaluator|
evaluator.inverse
end
self.class.new(inverse_body)
end
# Return evaluation
#
# @param [Input]
#
# @return [Evaluation::Nary]
#
# @api private
#
def evaluation(input)
evaluations = body.each_with_object([]) do |evaluator, aggregate|
evaluation = evaluator.evaluation(input)
aggregate << evaluation
return evaluation_error(input, aggregate) unless evaluation.success?
end
output = Hash[evaluations.map(&:output)]
Evaluation::Nary.new(
evaluator: self,
input: input,
evaluations: evaluations,
output: output,
success: true
)
end
# Build evaluator from node
#
# @param [Compiler] compiler
# @param [Node] node
#
# @return [Evaluator]
#
# @api private
#
def self.build(compiler, node)
body = node.children.map do |child|
compiler.call(child)
end
new(body)
end
end # HashTransform
end # Transformer
end # Evaluator
end # Morpher
Fix documentation
module Morpher
class Evaluator
class Transformer
# Too complex hash transformation evaluator
#
# FIXME: Shold be broken up in better primitives a decompose, compose pair
#
# @api private
#
class HashTransform < self
include Concord.new(:body)
register :hash_transform
# Test if evaluator is transitive
#
# FIXME: Needs to be calculated dynamically
#
# @return [true]
# if evaluator is transitive
#
# @return [false]
# otherwise
#
# @api private
#
def transitive?
body.all? do |evaluator|
self.class.is_transitive_keypair?(evaluator)
end
end
# Test if evaluator is a keypair
#
# FIXME: Refactor the need for this away.
#
# This is a side effect from this class is generally to big in sense of SRP.
# Must be refactorable away. But dunno now. Still exploring.
#
# @param [Evaluator]
#
# @api private
#
def self.is_transitive_keypair?(evaluator)
return false unless evaluator.kind_of?(Block)
body = evaluator.body
return false unless body.length == 3
fetch, operator, dump = body
fetch.kind_of?(Key::Fetch) && dump.kind_of?(Key::Dump) && operator.transitive?
end
# Call evaluator
#
# @param [Object] input
#
# @return [Object]
#
# @api private
#
def call(input)
content = body.map do |node|
node.call(input)
end
Hash[content]
end
# Return inverse evaluator
#
# @return [HashTransform]
#
# @api private
#
def inverse
inverse_body = body.map do |evaluator|
evaluator.inverse
end
self.class.new(inverse_body)
end
# Return evaluation
#
# @param [Input]
#
# @return [Evaluation::Nary]
#
# @api private
#
def evaluation(input)
evaluations = body.each_with_object([]) do |evaluator, aggregate|
evaluation = evaluator.evaluation(input)
aggregate << evaluation
return evaluation_error(input, aggregate) unless evaluation.success?
end
output = Hash[evaluations.map(&:output)]
Evaluation::Nary.new(
evaluator: self,
input: input,
evaluations: evaluations,
output: output,
success: true
)
end
# Build evaluator from node
#
# @param [Compiler] compiler
# @param [Node] node
#
# @return [Evaluator]
#
# @api private
#
def self.build(compiler, node)
body = node.children.map do |child|
compiler.call(child)
end
new(body)
end
end # HashTransform
end # Transformer
end # Evaluator
end # Morpher
|
require 'bundler'
Bundler.require
# load the Database and User model
require './model'
class SinatraWardenExample < Sinatra::Base
enable :sessions
register Sinatra::Flash
use Warden::Manager do |config|
# Tell Warden how to save our User info into a session.
# Sessions can only take strings, not Ruby code, we'll store
# the User's `id`
config.serialize_into_session{|user| user.id }
# Now tell Warden how to take what we've stored in the session
# and get a User from that information.
config.serialize_from_session{|id| User.get(id) }
config.scope_defaults :default,
# "strategies" is an array of named methods with which to
# attempt authentication. We have to define this later.
strategies: [:password],
# The action is a route to send the user to when
# warden.authenticate! returns a false answer. We'll show
# this route below.
action: 'auth/unauthenticated'
# When a user tries to log in and cannot, this specifies the
# app to send the user to.
config.failure_app = self
end
Warden::Manager.before_failure do |env,opts|
env['REQUEST_METHOD'] = 'POST'
end
Warden::Strategies.add(:password) do
def valid?
params['user'] && params['user']['username'] && params['user']['password']
end
def authenticate!
user = User.first(username: params['user']['username'])
if user.nil?
fail!("The username you entered does not exist.")
elsif user.authenticate(params['user']['password'])
success!(user)
else
fail!("Could not log in")
end
end
end
get '/' do
erb :index
end
get '/signup' do
erb :signup
end
post '/signup' do
@newu = params['username']
@newpass=params['password']
@user = User.create(username: @newu)
@user.password = @newpass
@user.save
end
get '/auth/login' do
erb :login
end
post '/auth/login' do
env['warden'].authenticate!
@currentuser=session["warden.user.default.key"]
flash[:success] = env['warden'].message
if session[:return_to].nil?
redirect "/userview/#{@currentuser}"
else
redirect session[:return_to]
end
end
get '/auth/logout' do
env['warden'].raw_session.inspect
env['warden'].logout
flash[:success] = 'Successfully logged out'
# redirect '/'
end
get '/userview/:id' do
if session["warden.user.default.key"]==params["id"].to_i
@active_matches = Match.all(:user1=> params["id"].to_i, :winner =>"0" )#get active matches
@active_matches2 = Match.all(:user2=> params["id"].to_i, :winner =>"0" )#get active matches
@completed_matches = Match.all(:user1=> params["id"].to_i, :winner =>"1") #get completed matches
@completed_matches2 = Match.all(:user2=> params["id"].to_i, :winner =>"1") #get completed matches
# binding.pry
erb :userview
else
redirect '/'
end
end
post '/auth/unauthenticated' do
session[:return_to] = env['warden.options'][:attempted_path] if session[:return_to].nil?
puts env['warden.options'][:attempted_path]
puts env['warden']
flash[:error] = env['warden'].message || "You must log in"
redirect '/auth/login'
end
get '/protected' do
env['warden'].authenticate!
erb :protected
end
get "/auth/challenge" do
env['warden'].raw_session.inspect
erb :challenge
end
post "/auth/rock_submit_primary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user1=> session["warden.user.default.key"])
binding.pry
#how do we get the user 2 id here?
@new_game= Game.create(match_id: @newmatch.first.id, user1_choice: "rock", user2_choice:"null for now")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/rock_submit_secondary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user2=> session["warden.user.default.key"])
binding.pry
@new_game= Game.create(match_id: @newmatch.first.id, user2_choice:"rock")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/paper_submit_primary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user1=> session["warden.user.default.key"])
binding.pry
#how do we get the user 2 id here?
@new_game= Game.create(match_id: @newmatch.first.id, user1_choice: "paper", user2_choice:"null for now")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/paper_submit_secondary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user2=> session["warden.user.default.key"])
binding.pry
@new_game= Game.create(match_id: @newmatch.first.id, user2_choice:"paper")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/scissors_submit_primary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user1=> session["warden.user.default.key"])
binding.pry
#how do we get the user 2 id here?
@new_game= Game.create(match_id: @newmatch.first.id, user1_choice: "scissors", user2_choice:"null for now")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/scissor_submit_secondary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user2=> session["warden.user.default.key"])
binding.pry
@new_game= Game.create(match_id: @newmatch.first.id, user2_choice:"scissors")
#this will cause bugs with multiple matches open.
erb :index
end
end
played with update function
require 'bundler'
Bundler.require
# load the Database and User model
require './model'
class SinatraWardenExample < Sinatra::Base
enable :sessions
register Sinatra::Flash
use Warden::Manager do |config|
# Tell Warden how to save our User info into a session.
# Sessions can only take strings, not Ruby code, we'll store
# the User's `id`
config.serialize_into_session{|user| user.id }
# Now tell Warden how to take what we've stored in the session
# and get a User from that information.
config.serialize_from_session{|id| User.get(id) }
config.scope_defaults :default,
# "strategies" is an array of named methods with which to
# attempt authentication. We have to define this later.
strategies: [:password],
# The action is a route to send the user to when
# warden.authenticate! returns a false answer. We'll show
# this route below.
action: 'auth/unauthenticated'
# When a user tries to log in and cannot, this specifies the
# app to send the user to.
config.failure_app = self
end
Warden::Manager.before_failure do |env,opts|
env['REQUEST_METHOD'] = 'POST'
end
Warden::Strategies.add(:password) do
def valid?
params['user'] && params['user']['username'] && params['user']['password']
end
def authenticate!
user = User.first(username: params['user']['username'])
if user.nil?
fail!("The username you entered does not exist.")
elsif user.authenticate(params['user']['password'])
success!(user)
else
fail!("Could not log in")
end
end
end
get '/' do
erb :index
end
get '/signup' do
erb :signup
end
post '/signup' do
@newu = params['username']
@newpass=params['password']
@user = User.create(username: @newu)
@user.password = @newpass
@user.save
end
get '/auth/login' do
erb :login
end
post '/auth/login' do
env['warden'].authenticate!
@currentuser=session["warden.user.default.key"]
flash[:success] = env['warden'].message
if session[:return_to].nil?
redirect "/userview/#{@currentuser}"
else
redirect session[:return_to]
end
end
get '/auth/logout' do
env['warden'].raw_session.inspect
env['warden'].logout
flash[:success] = 'Successfully logged out'
# redirect '/'
end
get '/userview/:id' do
if session["warden.user.default.key"]==params["id"].to_i
@active_matches = Match.all(:user1=> params["id"].to_i, :winner =>"0" )#get active matches
@active_matches2 = Match.all(:user2=> params["id"].to_i, :winner =>"0" )#get active matches
@completed_matches = Match.all(:user1=> params["id"].to_i, :winner =>"1") #get completed matches
@completed_matches2 = Match.all(:user2=> params["id"].to_i, :winner =>"1") #get completed matches
# binding.pry
erb :userview
else
redirect '/'
end
end
post '/auth/unauthenticated' do
session[:return_to] = env['warden.options'][:attempted_path] if session[:return_to].nil?
puts env['warden.options'][:attempted_path]
puts env['warden']
flash[:error] = env['warden'].message || "You must log in"
redirect '/auth/login'
end
get '/protected' do
env['warden'].authenticate!
erb :protected
end
get "/auth/challenge" do
env['warden'].raw_session.inspect
erb :challenge
end
post "/auth/rock_submit_primary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user1=> session["warden.user.default.key"])
binding.pry
#how do we get the user 2 id here?
@new_game= Game.create(match_id: @newmatch.first.id, user1_choice: "rock")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/rock_submit_secondary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user2=> session["warden.user.default.key"])
binding.pry
@new_game= Game.all(match_id: @newmatch.first.id, user2_choice:"rock")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/paper_submit_primary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user1=> session["warden.user.default.key"])
binding.pry
#how do we get the user 2 id here?
@new_game= Game.create(match_id: @newmatch.first.id, user1_choice: "paper", user2_choice:"null for now")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/paper_submit_secondary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user2=> session["warden.user.default.key"])
binding.pry
@new_game= Game.create(match_id: @newmatch.first.id, user2_choice:"paper")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/scissors_submit_primary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user1=> session["warden.user.default.key"])
binding.pry
#how do we get the user 2 id here?
@new_game= Game.create(match_id: @newmatch.first.id, user1_choice: "scissors", user2_choice:"null for now")
#this will cause bugs with multiple matches open.
erb :index
end
post "/auth/scissors_submit_secondary" do # submit button that updates sql table to reflect move
env['warden'].authenticate!
@newmatch= Match.all(:user2=> session["warden.user.default.key"])
binding.pry
@new_game= Game.get(match_id: @newmatch.first.id)
binding.pry
#this will cause bugs with multiple matches open.
erb :index
end
end |
require 'bundler/setup'
require 'sinatra'
require 'rest_client'
require 'json'
# !!! DO NOT EVER USE HARD-CODED VALUES IN A REAL APP !!!
# Instead, set and test environment variables, like below
# if ENV['GITHUB_CLIENT_ID'] && ENV['GITHUB_CLIENT_SECRET']
# CLIENT_ID = ENV['GITHUB_CLIENT_ID']
# CLIENT_SECRET = ENV['GITHUB_CLIENT_SECRET']
# end
CLIENT_ID = ENV['GH_BASIC_CLIENT_ID']
CLIENT_SECRET = ENV['GH_BASIC_SECRET_ID']
use Rack::Session::Pool, :cookie_only => false
get '/' do
erb :index
end
get '/login' do
redirect 'https://github.com/login/oauth/authorize?scope=public_repo&client_id=' + CLIENT_ID
end
get '/logout' do
session.clear
redirect '/'
end
get '/github-oauth-callback' do
session_code = request.env['rack.request.query_hash']['code']
result = RestClient.post('https://github.com/login/oauth/access_token',
{:client_id => CLIENT_ID,
:client_secret => CLIENT_SECRET,
:code => session_code},
:accept => :json)
session[:access_token] = JSON.parse(result)['access_token']
redirect '/'
end
get '/github-access-token' do
session[:access_token]
end
Respond to /github-access-token with 401 on failure
require 'bundler/setup'
require 'sinatra'
require 'rest_client'
require 'json'
# !!! DO NOT EVER USE HARD-CODED VALUES IN A REAL APP !!!
# Instead, set and test environment variables, like below
# if ENV['GITHUB_CLIENT_ID'] && ENV['GITHUB_CLIENT_SECRET']
# CLIENT_ID = ENV['GITHUB_CLIENT_ID']
# CLIENT_SECRET = ENV['GITHUB_CLIENT_SECRET']
# end
CLIENT_ID = ENV['GH_BASIC_CLIENT_ID']
CLIENT_SECRET = ENV['GH_BASIC_SECRET_ID']
use Rack::Session::Pool, :cookie_only => false
get '/' do
erb :index
end
get '/login' do
redirect 'https://github.com/login/oauth/authorize?scope=public_repo&client_id=' + CLIENT_ID
end
get '/logout' do
session.clear
redirect '/'
end
get '/github-oauth-callback' do
session_code = request.env['rack.request.query_hash']['code']
result = RestClient.post('https://github.com/login/oauth/access_token',
{:client_id => CLIENT_ID,
:client_secret => CLIENT_SECRET,
:code => session_code},
:accept => :json)
session[:access_token] = JSON.parse(result)['access_token']
redirect '/'
end
get '/github-access-token' do
status 401 unless session[:access_token]
session[:access_token]
end
|
# desc "Explaining what the task does"
# task :simple_navigation do
# # Task goes here
# end
tasks not needed at moment
|
require 'json'
package = JSON.parse(File.read(File.join('${REACT_NATIVE_PATH}', 'package.json')))
Pod::Spec.new do |s|
s.name = "RCTTest"
s.version = package['version']
s.summary = package['description']
s.description = 'RCTTest hack spec'
s.homepage = 'http://facebook.github.io/react-native/'
s.license = package['license']
s.author = "Facebook"
s.requires_arc = true
s.platform = :ios, "8.0"
s.header_dir = 'React'
s.source = { :git => "https://github.com/exponent/react-native.git" }
s.source_files = "Libraries/RCTTest/**/*.{h,m}"
s.preserve_paths = "Libraries/RCTTest/**/*.js"
s.frameworks = "XCTest"
end
Remove preserving JS files in RCTTest.podspec
fbshipit-source-id: 60b4b2e
require 'json'
package = JSON.parse(File.read(File.join('${REACT_NATIVE_PATH}', 'package.json')))
Pod::Spec.new do |s|
s.name = "RCTTest"
s.version = package['version']
s.summary = package['description']
s.description = 'RCTTest hack spec'
s.homepage = 'http://facebook.github.io/react-native/'
s.license = package['license']
s.author = "Facebook"
s.requires_arc = true
s.platform = :ios, "8.0"
s.header_dir = 'React'
s.source = { :git => "https://github.com/exponent/react-native.git" }
s.source_files = "Libraries/RCTTest/**/*.{h,m}"
s.frameworks = "XCTest"
end
|
Added dropbear ssh to post processing
# Copyright (c) 2010-2017 Jacob Hammack.
#
# 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 NON INFRINGEMENT. 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.
module Risu
module Parsers
module Nessus
module PostProcess
class DropbearSSHServerPatchRollup < Risu::Base::PostProcessBase
#
def initialize
@info =
{
:description => "Dropbear SSH Server Patch Rollup",
:plugin_id => -99952,
:plugin_name => "Update to the latest Dropbear SSH Server",
:item_name => "Update to the latest Dropbear SSH Server",
:plugin_ids => [
93650,
58183,
]
}
end
end
end
end
end
end
|
module LoadContainerServices
#@returns boolean
#load persistant and non persistant service definitions off disk and registers them
def load_and_attach_services(dirname,container)
clear_error
envs = []
curr_service_file = ''
Dir.glob(dirname + '/*.yaml').each do |service_file|
curr_service_file = service_file
yaml = File.read(service_file)
service_hash = YAML::load( yaml )
service_hash = SystemUtils.symbolize_keys(service_hash)
service_hash[:container_type] = container.ctype
ServiceDefinitions.set_top_level_service_params(service_hash, container.container_name)
if service_hash.has_key?(:shared_service) == false || service_hash[:shared_service] == false
templater = Templater.new(SystemAccess.new,container)
templater.proccess_templated_service_hash(service_hash)
SystemUtils.debug_output( :templated_service_hash, service_hash)
if service_hash[:persistant] == false || test_registry_result(system_registry_client.service_is_registered?(service_hash)) == false
add_service(service_hash)
else
service_hash = test_registry_result(system_registry_client.get_service_entry(service_hash))
end
else
p :finding_service_to_share
p service_hash
service_hash = test_registry_result(system_registry_client.get_service_entry(service_hash))
p :load_share_hash
p service_hash
end
if service_hash.is_a?(Hash)
SystemUtils.debug_output( :post_entry_service_hash, service_hash)
new_envs = SoftwareServiceDefinition.service_environments(service_hash)
p 'new_envs'
p new_envs.to_s
envs = EnvironmentVariable.merge_envs(new_envs,envs) unless new_envs.nil?
# envs.concat(new_envs) if !new_envs.nil?
else
log_error_mesg('failed to get service entry from ' ,service_hash)
end
end
return envs
rescue Exception=>e
puts e.message
log_error_mesg('Parse error on ' + curr_service_file,container)
log_exception(e)
end
end
use container envs to add to and no an empty array
module LoadContainerServices
#@returns boolean
#load persistant and non persistant service definitions off disk and registers them
def load_and_attach_services(dirname,container)
clear_error
envs = container.environments
envs = [] if envs.nil?
curr_service_file = ''
Dir.glob(dirname + '/*.yaml').each do |service_file|
curr_service_file = service_file
yaml = File.read(service_file)
service_hash = YAML::load( yaml )
service_hash = SystemUtils.symbolize_keys(service_hash)
service_hash[:container_type] = container.ctype
ServiceDefinitions.set_top_level_service_params(service_hash, container.container_name)
if service_hash.has_key?(:shared_service) == false || service_hash[:shared_service] == false
templater = Templater.new(SystemAccess.new,container)
templater.proccess_templated_service_hash(service_hash)
SystemUtils.debug_output( :templated_service_hash, service_hash)
if service_hash[:persistant] == false || test_registry_result(system_registry_client.service_is_registered?(service_hash)) == false
add_service(service_hash)
else
service_hash = test_registry_result(system_registry_client.get_service_entry(service_hash))
end
else
p :finding_service_to_share
p service_hash
service_hash = test_registry_result(system_registry_client.get_service_entry(service_hash))
p :load_share_hash
p service_hash
end
if service_hash.is_a?(Hash)
SystemUtils.debug_output( :post_entry_service_hash, service_hash)
new_envs = SoftwareServiceDefinition.service_environments(service_hash)
p 'new_envs'
p new_envs.to_s
envs = EnvironmentVariable.merge_envs(new_envs,envs) unless new_envs.nil?
# envs.concat(new_envs) if !new_envs.nil?
else
log_error_mesg('failed to get service entry from ' ,service_hash)
end
end
return envs
rescue Exception=>e
puts e.message
log_error_mesg('Parse error on ' + curr_service_file,container)
log_exception(e)
end
end |
# Copyright 2014 Netflix, Inc.
#
# 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.
require 'rest-client'
require 'byebug'
require 'base64'
class ScumblrTask::GithubEventAnalyzer < ScumblrTask::Base
include ActionView::Helpers::TextHelper
def self.task_type_name
"Github Event Analyzer"
end
def self.task_category
"Security"
end
def self.options
# these should be a hash (key: val pairs)
{
:severity => {name: "Finding Severity",
description: "Set severity to either observation, high, medium, or low",
required: true,
type: :choice,
default: :observation,
choices: [:observation, :high, :medium, :low]},
:github_terms => {name: "System Metadata Github Search Terms",
description: "Use system metadata search strings. Expectes metadata to be in JSON array format.",
required: true,
type: :system_metadata}
}
end
def initialize(options={})
super
end
def match_environment(vuln_url, content_response, hit_hash, regular_expressions, commit_email, commit_name, commit_branch)
vulnerabilities = []
before = {}
after ={}
regular_expressions_union = Regexp.union(regular_expressions.map {|x| Regexp.new(x.strip)})
term_counter = {}
contents = content_response
contents = contents.split(/\r?\n|\r/)
# Iterate through each line of the response and grep for the response_sring provided
contents.each_with_index do |line, line_no|
begin
searched_code = regular_expressions_union.match(line.encode("UTF-8", invalid: :replace, undef: :replace))
rescue
next
end
if searched_code
# puts "----Got Match!----\n"
# puts searched_code.to_s
term = ""
details = ""
matched_term = ""
regular_expressions.each_with_index do |expression, index|
if Regexp.new(expression).match(line.encode("UTF-8", invalid: :replace, undef: :replace))
matched_term = regular_expressions[index]
break
end
end
hit_hash.each do |hit|
if matched_term.to_s == hit[:regex]
term = hit[:name]
details = '"' + term + '"' + " Match"
end
end
if term_counter[term].to_i < 1
term_counter[term] = 1
vuln = Vulnerability.new
vuln.regex = matched_term
vuln.source = "github_event"
vuln.task_id = @options[:_self].id.to_s
vuln.term = term
vuln.details = details
if @options[:severity].nil?
vuln.severity = "observation"
else
vuln.severity = @options[:severity]
end
case line_no
when 0
before = nil
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2].to_s, length: 500), line_no + 3 => truncate(contents[line_no + 3].to_s, length: 500)}
when 1
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500)}
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2].to_s, length: 500), line_no + 3 => truncate(contents[line_no + 3].to_s, length: 500)}
when 2
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500)}
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2].to_s, length: 500), line_no + 3 => truncate(contents[line_no + 3].to_s, length: 500)}
when contents.length
after = nil
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500), line_no - 3 => truncate(contents[line_no - 3].to_s, length: 500)}
when contents.length - 1
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500)}
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500), line_no - 3 => truncate(contents[line_no - 3].to_s, length: 500)}
when contents.length - 2
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2])}
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500), line_no - 3 => truncate(contents[line_no - 3].to_s, length: 500)}
else
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500), line_no - 3 => truncate(contents[line_no - 3].to_s, length: 500)}
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2].to_s, length: 500), line_no + 3 => truncate(contents[line_no + 3].to_s, length: 500)}
end
# vuln.term = searched_code.to_s
vuln.url = vuln_url
vuln.code_fragment = truncate(line.chomp, length: 500)
vuln.commit_email = commit_email
vuln.commit_name = commit_name
vuln.commit_branch = commit_branch
vuln.match_location = "file"
vuln.before = before
vuln.after = after
vuln.line_number = line_no
vulnerabilities << vuln
else
term_counter[term] += 1
end
end
end
vulnerabilities.each do |vuln|
vuln.match_count = term_counter[vuln.term]
end
puts vulnerabilities.inspect
return vulnerabilities
end
def run
response = ""
begin
response = JSON.parse(@options[:_params][:_body])
rescue
puts 'not valid json'
end
vuln_object = {}
vulnerabilities = []
# Step through each finding and it's assocaited contents
response["findings"].each do |finding|
finding["findings"].each do | content |
vuln = Vulnerability.new
url = response["commit"]["repository"]["html_url"]
#vuln_url = content["content_urls"]
hits_to_search = content["hits"]
commit_email = response["commit"]["head_commit"]["committer"]["email"]
commit_name = response["commit"]["head_commit"]["committer"]["name"]
commit_branch = response["commit"]["ref"].split('/').last
# Step into the finding and create the right things:
hit_hash = []
regular_expressions = []
content["hits"].each do |hit|
response["config"]["regex_list"].each do |regex|
if regex["name"] == hit
regular_expressions << regex["regex"]
hit_hash << {"name": hit, "regex": regex["regex"]}
end
end
end
content_response = JSON.parse RestClient.get(content["content_urls"])
vuln_url = content_response["html_url"]
content_response = Base64.decode64(content_response["content"].strip)
puts content["hits"]
vulnerabilities = match_environment(vuln_url, content_response, hit_hash, regular_expressions, commit_email, commit_name, commit_branch)
@res = Result.where(url: url).first
@res.update_vulnerabilities(vulnerabilities)
# determine_term(response["config"], )
end
end
@res.save if @res.changed?
#puts "*****Running with options: " + @options[:_params].to_s
end
end
Update github_event_analyzer.rb
Removing byebug
# Copyright 2014 Netflix, Inc.
#
# 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.
require 'rest-client'
require 'base64'
class ScumblrTask::GithubEventAnalyzer < ScumblrTask::Base
include ActionView::Helpers::TextHelper
def self.task_type_name
"Github Event Analyzer"
end
def self.task_category
"Security"
end
def self.options
# these should be a hash (key: val pairs)
{
:severity => {name: "Finding Severity",
description: "Set severity to either observation, high, medium, or low",
required: true,
type: :choice,
default: :observation,
choices: [:observation, :high, :medium, :low]},
:github_terms => {name: "System Metadata Github Search Terms",
description: "Use system metadata search strings. Expectes metadata to be in JSON array format.",
required: true,
type: :system_metadata}
}
end
def initialize(options={})
super
end
def match_environment(vuln_url, content_response, hit_hash, regular_expressions, commit_email, commit_name, commit_branch)
vulnerabilities = []
before = {}
after ={}
regular_expressions_union = Regexp.union(regular_expressions.map {|x| Regexp.new(x.strip)})
term_counter = {}
contents = content_response
contents = contents.split(/\r?\n|\r/)
# Iterate through each line of the response and grep for the response_sring provided
contents.each_with_index do |line, line_no|
begin
searched_code = regular_expressions_union.match(line.encode("UTF-8", invalid: :replace, undef: :replace))
rescue
next
end
if searched_code
# puts "----Got Match!----\n"
# puts searched_code.to_s
term = ""
details = ""
matched_term = ""
regular_expressions.each_with_index do |expression, index|
if Regexp.new(expression).match(line.encode("UTF-8", invalid: :replace, undef: :replace))
matched_term = regular_expressions[index]
break
end
end
hit_hash.each do |hit|
if matched_term.to_s == hit[:regex]
term = hit[:name]
details = '"' + term + '"' + " Match"
end
end
if term_counter[term].to_i < 1
term_counter[term] = 1
vuln = Vulnerability.new
vuln.regex = matched_term
vuln.source = "github_event"
vuln.task_id = @options[:_self].id.to_s
vuln.term = term
vuln.details = details
if @options[:severity].nil?
vuln.severity = "observation"
else
vuln.severity = @options[:severity]
end
case line_no
when 0
before = nil
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2].to_s, length: 500), line_no + 3 => truncate(contents[line_no + 3].to_s, length: 500)}
when 1
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500)}
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2].to_s, length: 500), line_no + 3 => truncate(contents[line_no + 3].to_s, length: 500)}
when 2
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500)}
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2].to_s, length: 500), line_no + 3 => truncate(contents[line_no + 3].to_s, length: 500)}
when contents.length
after = nil
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500), line_no - 3 => truncate(contents[line_no - 3].to_s, length: 500)}
when contents.length - 1
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500)}
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500), line_no - 3 => truncate(contents[line_no - 3].to_s, length: 500)}
when contents.length - 2
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2])}
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500), line_no - 3 => truncate(contents[line_no - 3].to_s, length: 500)}
else
before = {line_no - 1 => truncate(contents[line_no - 1].to_s, length: 500), line_no - 2 => truncate(contents[line_no - 2].to_s, length: 500), line_no - 3 => truncate(contents[line_no - 3].to_s, length: 500)}
after = {line_no + 1 => truncate(contents[line_no + 1].to_s, length: 500), line_no + 2 => truncate(contents[line_no + 2].to_s, length: 500), line_no + 3 => truncate(contents[line_no + 3].to_s, length: 500)}
end
# vuln.term = searched_code.to_s
vuln.url = vuln_url
vuln.code_fragment = truncate(line.chomp, length: 500)
vuln.commit_email = commit_email
vuln.commit_name = commit_name
vuln.commit_branch = commit_branch
vuln.match_location = "file"
vuln.before = before
vuln.after = after
vuln.line_number = line_no
vulnerabilities << vuln
else
term_counter[term] += 1
end
end
end
vulnerabilities.each do |vuln|
vuln.match_count = term_counter[vuln.term]
end
puts vulnerabilities.inspect
return vulnerabilities
end
def run
response = ""
begin
response = JSON.parse(@options[:_params][:_body])
rescue
puts 'not valid json'
end
vuln_object = {}
vulnerabilities = []
# Step through each finding and it's assocaited contents
response["findings"].each do |finding|
finding["findings"].each do | content |
vuln = Vulnerability.new
url = response["commit"]["repository"]["html_url"]
#vuln_url = content["content_urls"]
hits_to_search = content["hits"]
commit_email = response["commit"]["head_commit"]["committer"]["email"]
commit_name = response["commit"]["head_commit"]["committer"]["name"]
commit_branch = response["commit"]["ref"].split('/').last
# Step into the finding and create the right things:
hit_hash = []
regular_expressions = []
content["hits"].each do |hit|
response["config"]["regex_list"].each do |regex|
if regex["name"] == hit
regular_expressions << regex["regex"]
hit_hash << {"name": hit, "regex": regex["regex"]}
end
end
end
content_response = JSON.parse RestClient.get(content["content_urls"])
vuln_url = content_response["html_url"]
content_response = Base64.decode64(content_response["content"].strip)
puts content["hits"]
vulnerabilities = match_environment(vuln_url, content_response, hit_hash, regular_expressions, commit_email, commit_name, commit_branch)
@res = Result.where(url: url).first
@res.update_vulnerabilities(vulnerabilities)
# determine_term(response["config"], )
end
end
@res.save if @res.changed?
#puts "*****Running with options: " + @options[:_params].to_s
end
end
|
require 'date'
require 'ostruct'
module SmartAnswer::Calculators
class HolidayEntitlement < OpenStruct
# created for the holiday entitlement calculator
MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT = 28.0
def full_time_part_time_days
days = (5.6 * fraction_of_year * days_per_week).round(10)
days > days_cap ? days_cap : days
end
def full_time_part_time_hours
(hours_per_week.to_f / days_per_week * MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT * fraction_of_year).round(10)
end
def full_time_part_time_hours_and_minutes
(full_time_part_time_hours * 60).ceil.divmod(60).map(&:ceil)
end
def casual_irregular_entitlement
minutes = 5.6 / 46.4 * total_hours * 60
minutes.ceil.divmod(60).map(&:ceil)
end
def annualised_hours_per_week
(total_hours / 46.4).round(10)
end
def annualised_entitlement
# These are the same at the moment
casual_irregular_entitlement
end
def compressed_hours_entitlement
minutes = 5.6 * hours_per_week * 60
minutes.ceil.divmod(60).map(&:ceil)
end
def compressed_hours_daily_average
minutes = hours_per_week.to_f / days_per_week * 60
minutes.ceil.divmod(60).map(&:ceil)
end
def shift_entitlement
(5.6 * fraction_of_year * shifts_per_week).round(10)
end
def fraction_of_year
return 1 if self.start_date.nil? && self.leaving_date.nil?
days_divide = leave_year_range.leap? ? 366 : 365
if start_date && leaving_date
(leaving_date - start_date + 1.0) / days_divide
elsif leaving_date
(leaving_date - leave_year_range.begins_on + 1.0) / days_divide
else
(leave_year_range.ends_on - start_date + 1.0) / days_divide
end
end
def formatted_fraction_of_year(dp = 2)
format_number(fraction_of_year, dp)
end
def strip_zeros(number)
number.to_s.sub(/\.0+$/, '')
end
def method_missing(symbol, *args)
# formatted_foo calls format_number on foo
formatting_method = formatting_method(symbol)
if formatting_method
format_number(send(formatting_method), args.first || 1)
else
super
end
end
def respond_to?(symbol, include_all = false)
formatting_method(symbol).present? || super
end
private
def formatting_method(symbol)
matches = symbol.to_s.match(/\Aformatted_(.*)\z/)
matches ? matches[1].to_sym : nil
end
def leave_year_range
leave_year_start = self.leave_year_start_date || "1 January"
SmartAnswer::YearRange.resetting_on(leave_year_start).including(date_calc)
end
def shifts_per_week
(shifts_per_shift_pattern.to_f / days_per_shift_pattern.to_f * 7).round(10)
end
def date_calc
if self.start_date
start_date
else
leaving_date
end
end
def format_number(number, decimal_places = 1)
rounded = (number * 10**decimal_places).ceil.to_f / 10**decimal_places
str = sprintf("%.#{decimal_places}f", rounded)
strip_zeros(str)
end
def days_cap
(MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT * fraction_of_year).round(10)
end
end
end
Make it clear that MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT is in days
require 'date'
require 'ostruct'
module SmartAnswer::Calculators
class HolidayEntitlement < OpenStruct
# created for the holiday entitlement calculator
MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT_IN_DAYS = 28.0
def full_time_part_time_days
days = (5.6 * fraction_of_year * days_per_week).round(10)
days > days_cap ? days_cap : days
end
def full_time_part_time_hours
(hours_per_week.to_f / days_per_week * MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT_IN_DAYS * fraction_of_year).round(10)
end
def full_time_part_time_hours_and_minutes
(full_time_part_time_hours * 60).ceil.divmod(60).map(&:ceil)
end
def casual_irregular_entitlement
minutes = 5.6 / 46.4 * total_hours * 60
minutes.ceil.divmod(60).map(&:ceil)
end
def annualised_hours_per_week
(total_hours / 46.4).round(10)
end
def annualised_entitlement
# These are the same at the moment
casual_irregular_entitlement
end
def compressed_hours_entitlement
minutes = 5.6 * hours_per_week * 60
minutes.ceil.divmod(60).map(&:ceil)
end
def compressed_hours_daily_average
minutes = hours_per_week.to_f / days_per_week * 60
minutes.ceil.divmod(60).map(&:ceil)
end
def shift_entitlement
(5.6 * fraction_of_year * shifts_per_week).round(10)
end
def fraction_of_year
return 1 if self.start_date.nil? && self.leaving_date.nil?
days_divide = leave_year_range.leap? ? 366 : 365
if start_date && leaving_date
(leaving_date - start_date + 1.0) / days_divide
elsif leaving_date
(leaving_date - leave_year_range.begins_on + 1.0) / days_divide
else
(leave_year_range.ends_on - start_date + 1.0) / days_divide
end
end
def formatted_fraction_of_year(dp = 2)
format_number(fraction_of_year, dp)
end
def strip_zeros(number)
number.to_s.sub(/\.0+$/, '')
end
def method_missing(symbol, *args)
# formatted_foo calls format_number on foo
formatting_method = formatting_method(symbol)
if formatting_method
format_number(send(formatting_method), args.first || 1)
else
super
end
end
def respond_to?(symbol, include_all = false)
formatting_method(symbol).present? || super
end
private
def formatting_method(symbol)
matches = symbol.to_s.match(/\Aformatted_(.*)\z/)
matches ? matches[1].to_sym : nil
end
def leave_year_range
leave_year_start = self.leave_year_start_date || "1 January"
SmartAnswer::YearRange.resetting_on(leave_year_start).including(date_calc)
end
def shifts_per_week
(shifts_per_shift_pattern.to_f / days_per_shift_pattern.to_f * 7).round(10)
end
def date_calc
if self.start_date
start_date
else
leaving_date
end
end
def format_number(number, decimal_places = 1)
rounded = (number * 10**decimal_places).ceil.to_f / 10**decimal_places
str = sprintf("%.#{decimal_places}f", rounded)
strip_zeros(str)
end
def days_cap
(MAXIMUM_STATUTORY_HOLIDAY_ENTITLEMENT_IN_DAYS * fraction_of_year).round(10)
end
end
end
|
module Tasks
module Concerns::Models::Taskables::Text::Request
extend ActiveSupport::Concern
included do
include ::Tasks::Taskables::Taskable
has_many :responses
responses are: :responses
def to_s
text
end
end
end
end
Add dependent: :destroy
module Tasks
module Concerns::Models::Taskables::Text::Request
extend ActiveSupport::Concern
included do
include ::Tasks::Taskables::Taskable
has_many :responses, dependent: :destroy
responses are: :responses
def to_s
text
end
end
end
end
|
require "formula"
class Sfmidi < Formula
homepage ""
url "http://www.zorexxlkl.com/files/downloads/sfMidi-1.1.0-CMake.zip"
sha1 "039edb82863e42bab213c6e60d9029396cb84d0b"
depends_on "cmake" => :build
depends_on "sfml" => :build
depends_on "fluidsynth" => :build
def install
# Include Error.h among installed header files
system '/usr/local/bin/gsed -i -e "s/.*Loader.h.*/\${INCSFMIDI}\/Loader.h\\n\${INCSFMIDI}\/Error.h/" CMakeLists.txt'
system "cmake", ".", *std_cmake_args
system "make", "install"
end
test do
system "#{bin}/program"
end
end
remove unneeded test
require "formula"
class Sfmidi < Formula
homepage ""
url "http://www.zorexxlkl.com/files/downloads/sfMidi-1.1.0-CMake.zip"
sha1 "039edb82863e42bab213c6e60d9029396cb84d0b"
depends_on "cmake" => :build
depends_on "sfml" => :build
depends_on "fluidsynth" => :build
def install
# Include Error.h among installed header files
system '/usr/local/bin/gsed -i -e "s/.*Loader.h.*/\${INCSFMIDI}\/Loader.h\\n\${INCSFMIDI}\/Error.h/" CMakeLists.txt'
system "cmake", ".", *std_cmake_args
system "make", "install"
end
end
|
Pod::Spec.new do |s|
s.name = 'FSHelper'
s.version = '1.0'
s.summary = 'Extensions for iOS'
s.homepage = 'https://github.com/fs/FSHelper'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Vladimir Goncharov' => 'vladimir1631@yandex.ru' }
s.platform = :ios, '5.0'
s.source = { :git => 'https://github.com/fs/FSHelper.git', :tag => s.version.to_s }
s.ios.source_files = 'Objective-C/*.{h,m}'
s.frameworks = 'Foundation', 'UIKit', 'QuartzCore', 'MapKit', 'Accelerate', 'ImageIO'
s.requires_arc = true
end
Update version to podspec
Pod::Spec.new do |s|
s.name = 'FSHelper'
s.version = '1.0.1'
s.summary = 'Extensions for iOS'
s.homepage = 'https://github.com/fs/FSHelper'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Vladimir Goncharov' => 'vladimir1631@yandex.ru' }
s.platform = :ios, '5.0'
s.source = { :git => 'https://github.com/fs/FSHelper.git', :tag => s.version.to_s }
s.ios.source_files = 'Objective-C/*.{h,m}'
s.frameworks = 'Foundation', 'UIKit', 'QuartzCore', 'MapKit', 'Accelerate', 'ImageIO'
s.requires_arc = true
end
|
require 'test_helper'
class WebService::ResourceTest < Test::Unit::TestCase
@@anonymous = Class.new(WebService::Resource)
@@anonymous_with_named_parent = Class.new(Foo)
# class
def test_element_name
# Anonymous class
assert_raise NameError do
@@anonymous.instance_eval { element_name }
end
# Named class
assert_equal "foo", Foo.instance_eval { element_name }
# Anonymous class with named parent
assert_equal "foo", @@anonymous_with_named_parent.instance_eval { element_name }
# Anonymous class with explicit element name
anonymous = Class.new(WebService::Resource)
anonymous.element_name = "bar"
assert_equal "bar", anonymous.element_name
end
def test_belongs_to
#########
# Save
#########
bar = Bar.new("foo" => Foo.new("id" => 1), "a" => "b")
expect_request bar,
:post, "/foos/1/bars", :body => {"bar" => {"foo_id" => 1, "a" => "b"}},
:return => {:status => "201", :body => {"bar" => {"c" => "d"}}}
bar.save
assert_equal({"c" => "d"}, bar.attributes)
##########
# Fetch
##########
expect_request Bar, :get, "/bars", :return => {:status => "200", :body => []}
Bar.all
end
def test_has_many
foo = Foo.new("id" => 1)
##################
# Instantiation
##################
bar = foo.bars.build("a" => "b")
assert_equal({"foo_id" => 1, "a" => "b"}, bar.attributes)
#############
# Fetching
#############
expect_request foo.bars,
:get, "/foos/1/bars",
:return => {:status => "200", :body => []}
foo.bars.all
end
# public
def test_to_hash
res = WebService::Resource.new(:foo => :bar)
assert_equal res.attributes, res.to_hash
end
def test_save
#############
# Creation
#############
foo = Foo.new("a" => "b")
expect_request foo,
:post, "/foos", :body => {"foo" => {"a" => "b"}},
:return => {:status => '201', :body => {"foo" => {"c" => "d"}}}
foo.save
assert_equal({"c" => "d"}, foo.attributes)
###########
# Update
###########
foo = Foo.new("id" => 1, "a" => "b")
expect_request foo,
:put, "/foos/1", :body => {"foo" => {"id" => 1, "a" => "b"}},
:return => {:status => "200", :body => {"foo" => {"c" => "d"}}}
foo.save
assert_equal({"c" => "d"}, foo.attributes)
##############
# Singleton
##############
type_foo = Class.new(Foo) { self.singleton = true }
# Creation
foo = type_foo.new
expect_request foo,
:post, "/foo", :body => {"foo" => {}},
:return => {:status => "201", :body => {"foo" => {}}}
foo.save
# Update
foo = type_foo.new("id" => 1)
expect_request foo,
:put, "/foo", :body => {"foo" => {"id" => 1}},
:return => {:status => "200", :body => {"foo" => {}}}
foo.save
end
end
made code-headings less prominent where appropriate
require 'test_helper'
class WebService::ResourceTest < Test::Unit::TestCase
@@anonymous = Class.new(WebService::Resource)
@@anonymous_with_named_parent = Class.new(Foo)
# class
def test_element_name
# Anonymous class
assert_raise NameError do
@@anonymous.instance_eval { element_name }
end
# Named class
assert_equal "foo", Foo.instance_eval { element_name }
# Anonymous class with named parent
assert_equal "foo", @@anonymous_with_named_parent.instance_eval { element_name }
# Anonymous class with explicit element name
anonymous = Class.new(WebService::Resource)
anonymous.element_name = "bar"
assert_equal "bar", anonymous.element_name
end
def test_belongs_to
# Saving
bar = Bar.new("foo" => Foo.new("id" => 1), "a" => "b")
expect_request bar,
:post, "/foos/1/bars", :body => {"bar" => {"foo_id" => 1, "a" => "b"}},
:return => {:status => "201", :body => {"bar" => {"c" => "d"}}}
bar.save
assert_equal({"c" => "d"}, bar.attributes)
# Fetching
expect_request Bar, :get, "/bars", :return => {:status => "200", :body => []}
Bar.all
end
def test_has_many
foo = Foo.new("id" => 1)
# Instantiation
bar = foo.bars.build("a" => "b")
assert_equal({"foo_id" => 1, "a" => "b"}, bar.attributes)
# Fetching
expect_request foo.bars,
:get, "/foos/1/bars",
:return => {:status => "200", :body => []}
foo.bars.all
end
# public
def test_to_hash
res = WebService::Resource.new(:foo => :bar)
assert_equal res.attributes, res.to_hash
end
def test_save
#############
# Creation
#############
foo = Foo.new("a" => "b")
expect_request foo,
:post, "/foos", :body => {"foo" => {"a" => "b"}},
:return => {:status => '201', :body => {"foo" => {"c" => "d"}}}
foo.save
assert_equal({"c" => "d"}, foo.attributes)
###########
# Update
###########
foo = Foo.new("id" => 1, "a" => "b")
expect_request foo,
:put, "/foos/1", :body => {"foo" => {"id" => 1, "a" => "b"}},
:return => {:status => "200", :body => {"foo" => {"c" => "d"}}}
foo.save
assert_equal({"c" => "d"}, foo.attributes)
##############
# Singleton
##############
type_foo = Class.new(Foo) { self.singleton = true }
# Creation
foo = type_foo.new
expect_request foo,
:post, "/foo", :body => {"foo" => {}},
:return => {:status => "201", :body => {"foo" => {}}}
foo.save
# Update
foo = type_foo.new("id" => 1)
expect_request foo,
:put, "/foo", :body => {"foo" => {"id" => 1}},
:return => {:status => "200", :body => {"foo" => {}}}
foo.save
end
end
|
# frozen_string_literal: true
#
# = AJAX Controller
#
# AJAX controller can take slightly "enhanced" URLs:
#
# http://domain.org/ajax/method
# http://domain.org/ajax/method/id
# http://domain.org/ajax/method/type/id
# http://domain.org/ajax/method/type/id?other=params
#
# Syntax of successful responses vary depending on the method.
#
# Errors are status 500, with the response body being the error message.
# Semantics of the possible error messages varies depending on the method.
#
# == Actions
#
# api_key:: Activate and edit ApiKey's.
# auto_complete:: Return list of strings matching a given string.
# create_image_object:: Uploads image without observation yet.
# exif:: Get EXIF header info of an image.
# export:: Change export status.
# external_link:: Add, edit and remove external links assoc. with obs.
# multi_image_template:: HTML template for uploaded image.
# old_translation:: Return an old TranslationString by version id.
# pivotal:: Pivotal requests: look up, vote, or comment on story.
# vote:: Change vote on proposed name or image.
#
class AjaxController < ApplicationController
require_dependency "ajax_controller/api_key"
require_dependency "ajax_controller/auto_complete"
require_dependency "ajax_controller/exif"
require_dependency "ajax_controller/export"
require_dependency "ajax_controller/external_link"
require_dependency "ajax_controller/old_translation"
require_dependency "ajax_controller/pivotal"
require_dependency "ajax_controller/upload_image"
require_dependency "ajax_controller/vote"
disable_filters
around_action :catch_ajax_errors
layout false
def catch_ajax_errors
prepare_parameters
yield
rescue StandardError => e
msg = e.to_s + "\n"
msg += backtrace(e) unless Rails.env.production?
render(plain: msg, status: :internal_server_error)
end
def prepare_parameters
@type = params[:type].to_s
@id = params[:id].to_s
@value = params[:value].to_s
end
def backtrace(exception)
result = ""
exception.backtrace.each do |line|
break if /action_controller.*perform_action/.match?(line)
result += line + "\n"
end
result
end
def session_user!
User.current = session_user || raise("Must be logged in.")
end
# Used by unit tests.
def test
render(plain: "test")
end
end
Added new ajax "module".
# frozen_string_literal: true
#
# = AJAX Controller
#
# AJAX controller can take slightly "enhanced" URLs:
#
# http://domain.org/ajax/method
# http://domain.org/ajax/method/id
# http://domain.org/ajax/method/type/id
# http://domain.org/ajax/method/type/id?other=params
#
# Syntax of successful responses vary depending on the method.
#
# Errors are status 500, with the response body being the error message.
# Semantics of the possible error messages varies depending on the method.
#
# == Actions
#
# api_key:: Activate and edit ApiKey's.
# auto_complete:: Return list of strings matching a given string.
# create_image_object:: Uploads image without observation yet.
# exif:: Get EXIF header info of an image.
# export:: Change export status.
# external_link:: Add, edit and remove external links assoc. with obs.
# multi_image_template:: HTML template for uploaded image.
# old_translation:: Return an old TranslationString by version id.
# pivotal:: Pivotal requests: look up, vote, or comment on story.
# vote:: Change vote on proposed name or image.
#
class AjaxController < ApplicationController
require_dependency "ajax_controller/api_key"
require_dependency "ajax_controller/auto_complete"
require_dependency "ajax_controller/exif"
require_dependency "ajax_controller/export"
require_dependency "ajax_controller/external_link"
require_dependency "ajax_controller/old_translation"
require_dependency "ajax_controller/pivotal"
require_dependency "ajax_controller/primers"
require_dependency "ajax_controller/upload_image"
require_dependency "ajax_controller/vote"
disable_filters
around_action :catch_ajax_errors
layout false
def catch_ajax_errors
prepare_parameters
yield
rescue StandardError => e
msg = e.to_s + "\n"
msg += backtrace(e) unless Rails.env.production?
render(plain: msg, status: :internal_server_error)
end
def prepare_parameters
@type = params[:type].to_s
@id = params[:id].to_s
@value = params[:value].to_s
end
def backtrace(exception)
result = ""
exception.backtrace.each do |line|
break if /action_controller.*perform_action/.match?(line)
result += line + "\n"
end
result
end
def session_user!
User.current = session_user || raise("Must be logged in.")
end
# Used by unit tests.
def test
render(plain: "test")
end
end
|
class AppsController < ApplicationController
respond_to :html, :json
layout :pick_layout
before_action :set_app, only: [:show, :edit, :destroy, :raw_simulator, :qr, :view, :fork]
before_action :authenticate_user!, only: [:index, :update, :destroy, :new]
before_action :paginate, only: [:popular, :search, :picks, :index]
acts_as_token_authentication_handler_for User, fallback: :none, only: :create
protect_from_forgery except: [:show, :create, :update, :fork]
def index
@apps = current_user.apps.order("updated_at desc")
respond_to do |format|
format.html
format.json do
@apps = @apps.limit(@per_page).offset(@offset)
render 'apps'
end
end
end
def qr
qr_code = GoogleQR.new(data: %({"bundle_path": "#{@app.bundle_path}", "module_name": "#{@app.module_name}"}), size: '250x250')
render json: {url: qr_code.to_s}
end
def search
@apps = App.where(["lower(name) LIKE lower(?)", "%#{params[:name]}%"]).limit(@per_page).offset(@offset)
render 'apps'
end
def picks
@apps = App.where(pick: true).order('updated_at desc').limit(@per_page).offset(@offset)
respond_to do |format|
format.html
format.json { render 'apps' }
end
end
def popular
@apps = App.order('view_count desc').order('updated_at desc').limit(@per_page).offset(@offset)
respond_to do |format|
format.html
format.json { render 'apps' }
end
end
def recent
@apps = App.where("name != 'Sample App' AND name != 'Sample App'").order('updated_at desc')
end
def log
logger.info params[:log]
end
def public
if params[:version].present?
@build = Build.where(name: params[:version]).first
@apps = @build.apps
else
@apps = App.where("name != 'Sample App'")
end
@apps = @apps.order("updated_at desc").all
respond_to do |format|
format.html
format.json { render json: @apps.to_json(include: {creator: {only: [:username, :avatar_url]}}, except: [:body, :bundle], methods: [:bundle_url])}
end
end
def public_index
@user = User.find_by(username: params[:username])
raise ActiveRecord::RecordNotFound if !@user
end
def raw_simulator
render layout: nil
end
def view
@app.increment_view_count!
respond_to do |format|
format.json do
render nothing: true
end
end
end
def show
@app.migrate_to_git if !@app.migrated_to_git?
@page_title = @app.name
@app.increment_view_count!
respond_to do |format|
format.html
end
end
def new
if !user_signed_in?
redirect_to new_user_session_path,
notice: 'Please sign in to create a new app'
else
@app = current_user.apps.create({
name: "Sample App",
module_name: "SampleApp",
build_id: Build.last.id,
created_from_web: true
})
redirect_to app_path(@app)
end
end
def fork
if !user_signed_in?
render json: {error: 'Please sign in to fork this app'}
else
@new_app = current_user.apps.create(name: @app.name, module_name: @app.module_name,
build_id: @app.build_id, forked_app: @app)
render json: {success: true, token: @new_app.url_token}
end
end
def edit
redirect_to app_path(@app), permanent: true
end
def create
if user_signed_in?
respond_to do |format|
if @app = current_user.apps.create(app_params)
session[:apps] = [] if !session[:apps]
session[:apps] << @app.id
format.html { redirect_to app_path(@app), notice: 'App was successfully created.' }
format.json { render :show, status: :created, location: @app }
else
format.html { render :new }
format.json { render json: @app.errors, status: :unprocessable_entity }
end
end
else
render json: {error: "You must provide a valid authentication token to create an app"}, status: :unauthorized
end
end
def update
@app = App.find(params[:id])
if (app_params[:pick] && current_user.admin?) || (user_signed_in? && @app.created_by?(current_user))
@app.update(app_params)
logger.info @app.errors.inspect
render json: {success: true}
else
render json: {error: 'Access denied'}
end
end
def destroy
redirect_to root_path unless user_signed_in? && @app.created_by?(current_user)
@app.destroy
respond_to do |format|
format.html { redirect_to apps_url, notice: 'App was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def paginate
@per_page = 10
@page = (params[:page] || 1).to_i
@offset = (@page - 1) * @per_page
end
def set_app
@app = params[:id] ? App.where(url_token: params[:id]).first : (Rails.env.development? || Rails.env.staging? ? App.first : App.find(7))
raise ActiveRecord::RecordNotFound if !@app
end
def app_params
params.require(:app).permit(:name, :body, :module_name, :author, :build_id, :pick, :uses_git)
end
def pick_layout
if params[:action] == 'edit' || params[:action] == 'show'
'editor'
else
'application'
end
end
end
Have a placeholder in page title if app name is empty
class AppsController < ApplicationController
respond_to :html, :json
layout :pick_layout
before_action :set_app, only: [:show, :edit, :destroy, :raw_simulator, :qr, :view, :fork]
before_action :authenticate_user!, only: [:index, :update, :destroy, :new]
before_action :paginate, only: [:popular, :search, :picks, :index]
acts_as_token_authentication_handler_for User, fallback: :none, only: :create
protect_from_forgery except: [:show, :create, :update, :fork]
def index
@apps = current_user.apps.order("updated_at desc")
respond_to do |format|
format.html
format.json do
@apps = @apps.limit(@per_page).offset(@offset)
render 'apps'
end
end
end
def qr
qr_code = GoogleQR.new(data: %({"bundle_path": "#{@app.bundle_path}", "module_name": "#{@app.module_name}"}), size: '250x250')
render json: {url: qr_code.to_s}
end
def search
@apps = App.where(["lower(name) LIKE lower(?)", "%#{params[:name]}%"]).limit(@per_page).offset(@offset)
render 'apps'
end
def picks
@apps = App.where(pick: true).order('updated_at desc').limit(@per_page).offset(@offset)
respond_to do |format|
format.html
format.json { render 'apps' }
end
end
def popular
@apps = App.order('view_count desc').order('updated_at desc').limit(@per_page).offset(@offset)
respond_to do |format|
format.html
format.json { render 'apps' }
end
end
def recent
@apps = App.where("name != 'Sample App' AND name != 'Sample App'").order('updated_at desc')
end
def log
logger.info params[:log]
end
def public
if params[:version].present?
@build = Build.where(name: params[:version]).first
@apps = @build.apps
else
@apps = App.where("name != 'Sample App'")
end
@apps = @apps.order("updated_at desc").all
respond_to do |format|
format.html
format.json { render json: @apps.to_json(include: {creator: {only: [:username, :avatar_url]}}, except: [:body, :bundle], methods: [:bundle_url])}
end
end
def public_index
@user = User.find_by(username: params[:username])
raise ActiveRecord::RecordNotFound if !@user
end
def raw_simulator
render layout: nil
end
def view
@app.increment_view_count!
respond_to do |format|
format.json do
render nothing: true
end
end
end
def show
@app.migrate_to_git if !@app.migrated_to_git?
@page_title = @app.name.present? ? @app.name : "Unnamed App"
@app.increment_view_count!
respond_to do |format|
format.html
end
end
def new
if !user_signed_in?
redirect_to new_user_session_path,
notice: 'Please sign in to create a new app'
else
@app = current_user.apps.create({
name: "Sample App",
module_name: "SampleApp",
build_id: Build.last.id,
created_from_web: true
})
redirect_to app_path(@app)
end
end
def fork
if !user_signed_in?
render json: {error: 'Please sign in to fork this app'}
else
@new_app = current_user.apps.create(name: @app.name, module_name: @app.module_name,
build_id: @app.build_id, forked_app: @app)
render json: {success: true, token: @new_app.url_token}
end
end
def edit
redirect_to app_path(@app), permanent: true
end
def create
if user_signed_in?
respond_to do |format|
if @app = current_user.apps.create(app_params)
session[:apps] = [] if !session[:apps]
session[:apps] << @app.id
format.html { redirect_to app_path(@app), notice: 'App was successfully created.' }
format.json { render :show, status: :created, location: @app }
else
format.html { render :new }
format.json { render json: @app.errors, status: :unprocessable_entity }
end
end
else
render json: {error: "You must provide a valid authentication token to create an app"}, status: :unauthorized
end
end
def update
@app = App.find(params[:id])
if (app_params[:pick] && current_user.admin?) || (user_signed_in? && @app.created_by?(current_user))
@app.update(app_params)
logger.info @app.errors.inspect
render json: {success: true}
else
render json: {error: 'Access denied'}
end
end
def destroy
redirect_to root_path unless user_signed_in? && @app.created_by?(current_user)
@app.destroy
respond_to do |format|
format.html { redirect_to apps_url, notice: 'App was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def paginate
@per_page = 10
@page = (params[:page] || 1).to_i
@offset = (@page - 1) * @per_page
end
def set_app
@app = params[:id] ? App.where(url_token: params[:id]).first : (Rails.env.development? || Rails.env.staging? ? App.first : App.find(7))
raise ActiveRecord::RecordNotFound if !@app
end
def app_params
params.require(:app).permit(:name, :body, :module_name, :author, :build_id, :pick, :uses_git)
end
def pick_layout
if params[:action] == 'edit' || params[:action] == 'show'
'editor'
else
'application'
end
end
end
|
class BidsController < ApplicationController
before_action :set_round, only: [:index, :create]
before_action :set_player, only: [:create]
def index
@bids = @round.bids.all
render :index, status: 200, locals: {errors: []}
end
def create
submit_bid = SubmitBid.new(@round, @player, bid_params[:number_of_tricks], bid_params[:suit])
submit_bid.call
@bids = @round.bids.all
if submit_bid.errors.empty?
render json: submit_bid.round, serializer: RoundSerializer, status: :created, locals: { errors: [] }
else
render json: { errors: submit_bid.errors }, status: :unprocessable_entity
end
end
private
def set_round
@round = Round.find(bid_params[:round_id])
end
def set_player
@player = Player.find_by(user: current_user)
end
def bid_params
params.permit(:round_id, :number_of_tricks, :suit)
end
end
Fix bug where users were being confused across multiple rounds
class BidsController < ApplicationController
before_action :set_round, only: [:index, :create]
before_action :set_player, only: [:create]
def create
submit_bid = SubmitBid.new(@round, @player, bid_params[:number_of_tricks], bid_params[:suit])
submit_bid.call
@bids = @round.bids.all
if submit_bid.errors.empty?
render json: submit_bid.round, serializer: RoundSerializer, status: :created, locals: { errors: [] }
else
render json: { errors: submit_bid.errors }, status: :unprocessable_entity
end
end
private
def set_round
@round = Round.find(bid_params[:round_id])
end
def set_player
@player = @round.game.players.find_by(user: current_user)
end
def bid_params
params.permit(:round_id, :number_of_tricks, :suit)
end
end
|
# (c) 2008-2011 by Allgemeinbildung e.V., Bremen, Germany
# This file is part of Communtu.
# Communtu is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Communtu 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 Public License for more details.
# You should have received a copy of the GNU Affero Public License
# along with Communtu. If not, see <http://www.gnu.org/licenses/>.
class CartController < ApplicationController
before_filter :login_required
def title
t(:bundle_editor)
end
def create
prepare_create
redirect_to "/packages"
end
def new_from_list
prepare_create
end
def create_from_list
prepare_create
err = ""
package_list = ""
# read package list from file
if !params[:file][:attachment].nil? and params[:file][:attachment]!="" then
package_list += params[:file][:attachment].read +" "
end
# get package list from text area
if !params[:package_list].nil? and params[:package_list]!="" then
package_list += params[:package_list]
end
# get an array of packages
package_list = package_list.gsub(/\n/," ").split(" ")
if !package_list.empty?
cart = Cart.find(session[:cart])
metas = {}
Metapackage.all.each do |m|
metas[m.debian_name] = m
end
package_list.each do |n|
package = BasePackage.find(:first, :conditions => ["name = ?",n])
if package.nil? then
package = metas[n]
end
if package.nil? then
err += n+" "
else
content = CartContent.new
content.cart_id = cart.id
content.base_package_id = package.id
content.save!
end
end
else
flash[:error] = t(:error_no_packages)
end
if err != ""
err=err.gsub("<","")
err=err.gsub(">","")
flash[:error] = t(:controller_cart_2, :message => err, :url => "/home/new_repository")
end
redirect_to "/packages"
end
def save
cart = Cart.find(session[:cart])
if editing_metapackage?
bundle_id = cart.metapackage_id
if bundle_id.nil?
redirect_to :controller => 'metapackages', :action => 'new_from_cart', :name => cart.name
else
redirect_to({:controller => 'metapackages', :action => 'edit_new_or_cart', :id => bundle_id})
end
else
cart.destroy
session[:cart] = nil
redirect_to "/packages"
end
end
def clear
if editing_metapackage?
cart = Cart.find(session[:cart])
cart.destroy
session[:cart] = nil
end
render_cart
end
def add_to_cart
if editing_metapackage?
package = BasePackage.find(params[:id])
cart = Cart.find(session[:cart])
content = CartContent.new
content.cart_id = cart.id
content.base_package_id = package.id
content.save!
end
render_cart
end
def add_to_cart_box
if editing_metapackage?
package = BasePackage.find(params[:id])
cart = Cart.find(session[:cart])
content = CartContent.new
content.cart_id = cart.id
content.base_package_id = package.id
content.save!
end
render_cart_box
end
def rem_from_cart
if editing_metapackage?
cart = Cart.find(session[:cart])
content = CartContent.find(:first, :conditions => ["cart_id = ? and base_package_id = ?", cart.id, params[:id]])
if !content.nil? then content.destroy end
end
render_cart
end
def render_cart
respond_to do |wants|
wants.js { render :partial => 'metacart.html.erb'}
end
end
def render_cart_box
respond_to do |wants|
wants.js { render :partial => 'metacart_box.html.erb' }
end
end
end
working on #1452
# (c) 2008-2011 by Allgemeinbildung e.V., Bremen, Germany
# This file is part of Communtu.
# Communtu is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Communtu 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 Public License for more details.
# You should have received a copy of the GNU Affero Public License
# along with Communtu. If not, see <http://www.gnu.org/licenses/>.
class CartController < ApplicationController
before_filter :login_required
def title
t(:bundle_editor)
end
def create
prepare_create
redirect_to "/packages"
end
def new_from_list
prepare_create
end
def create_from_list
prepare_create
err = ""
package_list = ""
# read package list from file
if !params[:file][:attachment].nil? and params[:file][:attachment]!="" then
package_list += (params[:file][:attachment].read +" ")
end
# get package list from text area
if !params[:package_list].nil? and params[:package_list]!="" then
package_list += params[:package_list]
end
# get an array of packages
package_list = package_list.gsub(/\n/," ").split(" ")
if !package_list.empty?
cart = Cart.find(session[:cart])
metas = {}
Metapackage.all.each do |m|
metas[m.debian_name] = m
end
package_list.each do |n|
package = BasePackage.find(:first, :conditions => ["name = ?",n])
if package.nil? then
package = metas[n]
end
if package.nil? then
err += n+" "
else
content = CartContent.new
content.cart_id = cart.id
content.base_package_id = package.id
content.save!
end
end
else
flash[:error] = t(:error_no_packages)
end
if err != ""
err=err.gsub("<","")
err=err.gsub(">","")
flash[:error] = t(:controller_cart_2, :message => err, :url => "/home/new_repository")
end
redirect_to "/packages"
end
def save
cart = Cart.find(session[:cart])
if editing_metapackage?
bundle_id = cart.metapackage_id
if bundle_id.nil?
redirect_to :controller => 'metapackages', :action => 'new_from_cart', :name => cart.name
else
redirect_to({:controller => 'metapackages', :action => 'edit_new_or_cart', :id => bundle_id})
end
else
cart.destroy
session[:cart] = nil
redirect_to "/packages"
end
end
def clear
if editing_metapackage?
cart = Cart.find(session[:cart])
cart.destroy
session[:cart] = nil
end
render_cart
end
def add_to_cart
if editing_metapackage?
package = BasePackage.find(params[:id])
cart = Cart.find(session[:cart])
content = CartContent.new
content.cart_id = cart.id
content.base_package_id = package.id
content.save!
end
render_cart
end
def add_to_cart_box
if editing_metapackage?
package = BasePackage.find(params[:id])
cart = Cart.find(session[:cart])
content = CartContent.new
content.cart_id = cart.id
content.base_package_id = package.id
content.save!
end
render_cart_box
end
def rem_from_cart
if editing_metapackage?
cart = Cart.find(session[:cart])
content = CartContent.find(:first, :conditions => ["cart_id = ? and base_package_id = ?", cart.id, params[:id]])
if !content.nil? then content.destroy end
end
render_cart
end
def render_cart
respond_to do |wants|
wants.js { render :partial => 'metacart.html.erb'}
end
end
def render_cart_box
respond_to do |wants|
wants.js { render :partial => 'metacart_box.html.erb' }
end
end
end
|
#
# There was once a free software demo of chat in rails.
# Eventually, the code was taken offline by the author.
# and later ended up in Toombila.
#
# This chat is inspired by the code from toombila.
#
class ChatController < ApplicationController
include ChatHelper
stylesheet 'chat'
stylesheet 'groups'
permissions 'chat'
before_filter :login_required
prepend_before_filter :get_channel_and_user, :except => :index
append_before_filter :breadcrumbs
# show a list of available channels
def index
if logged_in?
@groups = current_user.all_groups
channel_users = {}
@groups.each do |group|
channel_users[group] = group.chat_channel ? group.chat_channel.users.size : 0
end
@group_array = channel_users.sort {|a,b| a[1] <=> b[1]}
@group_array.reverse!
end
end
# http request front door
# everything else is xhr request.
def channel
user_joins_channel(@user, @channel)
@messages = [@channel_user.join_message]
message_id = @messages.last.id
session[:first_retrieved_message_id] = message_id
session[:last_retrieved_message_id] = message_id
@channel_user.record_user_action :not_typing
@html_title = Time.zone.now.strftime('%Y.%m.%d')
end
# Post a user's message to a channel
def say
return false unless request.xhr?
# Get the message
message = params[:message]
return false unless message
if message.match(/^\/\w+/)
# It's an IRC style command
command, arguments = message.scan(/^\/(\w+)(.+?)$/).flatten
logger.info(command)
case command
when 'me'
@message = user_action_in_channel(@user, @channel, arguments)
else
return false
end
else
@message = user_say_in_channel(@user, @channel, message)
end
@channel_user.record_user_action :just_finished_typing
render :layout => false
end
def user_is_typing
return false unless request.xhr?
@channel_user.record_user_action :typing
render :nothing => true
end
# Get the latest messages since the user last got any
def poll_channel_for_updates
return false unless request.xhr?
# get latest messages, update id of last seen message
@messages = @channel.messages.since(session[:last_retrieved_message_id])
session[:last_retrieved_message_id] = @messages.last.id if @messages.any?
# deleted messages
@deleted_messages = ChatMessage.all(:conditions => ["id > ? AND channel_id = ? AND deleted_at IS NOT NULL", session[:first_retrieved_message_id], @channel.id])
@channel_user.record_user_action :not_typing
render :layout => false
end
def user_list
render :partial => 'chat/userlist', :layout => false
end
def leave_channel
user_leaves_channel(@user, @channel)
@channel_user.destroy
redirect_to :controller => :me, :action => :dashboard
end
def archive
@months = @channel.messages.months
unless @months.empty?
@current_year = Time.zone.now.year
@start_year = @months[0]['year'] || @current_year.to_s
@current_month = Time.zone.now.month
@date = params[:date] ? params[:date] : "%s-%s" % [@months.last['year'], @months.last['month']]
@date =~ /(\d{4})-(\d{1,2})-?(\d{0,2})/
@year = $1
@month = $2
@day = $3
unless @day.empty?
@messages = @channel.messages.for_day(@year, @month, @day)
@html_title = Time.zone.local(@year, @month, @day).strftime('%Y.%m.%d')
else
@days = @channel.messages.days(@year, @month)
end
end
end
private
# Get channel and user info that most methods use
def get_channel_and_user
@user = current_user
@channel = ChatChannel.find_by_id(params[:id]) if params[:id] !~ /\D/
unless @channel
@group = Group.find_by_name(params[:id])
if @group
@channel = ChatChannel.find_by_group_id(@group.id)
unless @channel
@channel = ChatChannel.create(:name => @group.name, :group_id => @group.id)
end
end
end
@channel_user = ChatChannelsUser.find(:first,
:conditions => {:channel_id => @channel,
:user_id => @user})
if (!@channel_user and (@user.is_a? User) and (action_name != 'archive'))
@channel_user = ChatChannelsUser.create!({:channel => @channel, :user => @user})
end
true
end
def user_say_in_channel(user, channel, say)
say = sanitize(say)
#say = say.gsub(":)", "<img src='../images/emoticons/smiley.png' \/>")
ChatMessage.create(:channel => channel, :content => say, :sender => user)
end
def user_action_in_channel(user, channel, say)
ChatMessage.create(:channel => channel, :content => sanitize(say), :sender => user, :level => 'action')
end
def user_joins_channel(user, channel)
ChatMessage.create(:channel => channel, :sender => user, :content => I18n.t(:joins_the_chatroom), :level => 'sys')
end
def user_leaves_channel(user, channel)
ChatMessage.create(:channel => channel, :sender => user, :content => I18n.t(:left_the_chatroom), :level => 'sys')
end
def sanitize(say)
# we'll use GreenCloth to process the say string ---
# this makes links clickable, and allows inline images,
# and can easily be extended to use smilies, etc...
#
# the only trick is that GreenCloth returns the text wrapped
# in a paragraph block (<p> stuff </p>), and things will
# look funny if we don't strip that off
say = GreenCloth.new(say).to_html
say.gsub! /\A<p>(.+)<\/p>\Z/m, '\1'
return say
end
def breadcrumbs
add_context 'chat', '/chat'
add_context @channel.name, url_for(:controller => 'chat', :action => 'channel', :id => @channel.name) if @channel
@active_tab = :chat
end
end
fixes #1831
#
# There was once a free software demo of chat in rails.
# Eventually, the code was taken offline by the author.
# and later ended up in Toombila.
#
# This chat is inspired by the code from toombila.
#
class ChatController < ApplicationController
include ChatHelper
stylesheet 'chat'
stylesheet 'groups'
permissions 'chat'
before_filter :login_required
prepend_before_filter :get_channel_and_user, :except => :index
append_before_filter :breadcrumbs
# show a list of available channels
def index
if logged_in?
@groups = current_user.all_groups
channel_users = {}
@groups.each do |group|
channel_users[group] = group.chat_channel ? group.chat_channel.users.size : 0
end
@group_array = channel_users.sort {|a,b| a[1] <=> b[1]}
@group_array.reverse!
end
end
# http request front door
# everything else is xhr request.
def channel
user_joins_channel(@user, @channel)
@messages = [@channel_user.join_message]
message_id = @messages.last.id
session[:first_retrieved_message_id] = message_id
session[:last_retrieved_message_id] = message_id
@channel_user.record_user_action :not_typing
@html_title = Time.zone.now.strftime('%Y.%m.%d')
end
# Post a user's message to a channel
def say
return false unless request.xhr?
# Get the message
message = params[:message]
return false unless message
if message.match(/^\/\w+/)
# It's an IRC style command
command, arguments = message.scan(/^\/(\w+)(.+?)$/).flatten
logger.info(command)
case command
when 'me'
@message = user_action_in_channel(@user, @channel, arguments)
else
return false
end
else
@message = user_say_in_channel(@user, @channel, message)
end
@channel_user.record_user_action :just_finished_typing
render :layout => false
end
def user_is_typing
return false unless request.xhr?
@channel_user.record_user_action :typing
render :nothing => true
end
# Get the latest messages since the user last got any
def poll_channel_for_updates
return false unless request.xhr?
# get latest messages, update id of last seen message
@messages = @channel.messages.since(session[:last_retrieved_message_id])
session[:last_retrieved_message_id] = @messages.last.id if @messages.any?
# deleted messages
@deleted_messages = ChatMessage.all(:conditions => ["id > ? AND channel_id = ? AND deleted_at IS NOT NULL", session[:first_retrieved_message_id], @channel.id])
@channel_user.record_user_action :not_typing
render :layout => false
end
def user_list
render :partial => 'chat/userlist', :layout => false
end
def leave_channel
user_leaves_channel(@user, @channel)
@channel_user.destroy
redirect_to my_work_me_pages_path
end
def archive
@months = @channel.messages.months
unless @months.empty?
@current_year = Time.zone.now.year
@start_year = @months[0]['year'] || @current_year.to_s
@current_month = Time.zone.now.month
@date = params[:date] ? params[:date] : "%s-%s" % [@months.last['year'], @months.last['month']]
@date =~ /(\d{4})-(\d{1,2})-?(\d{0,2})/
@year = $1
@month = $2
@day = $3
unless @day.empty?
@messages = @channel.messages.for_day(@year, @month, @day)
@html_title = Time.zone.local(@year, @month, @day).strftime('%Y.%m.%d')
else
@days = @channel.messages.days(@year, @month)
end
end
end
private
# Get channel and user info that most methods use
def get_channel_and_user
@user = current_user
@channel = ChatChannel.find_by_id(params[:id]) if params[:id] !~ /\D/
unless @channel
@group = Group.find_by_name(params[:id])
if @group
@channel = ChatChannel.find_by_group_id(@group.id)
unless @channel
@channel = ChatChannel.create(:name => @group.name, :group_id => @group.id)
end
end
end
@channel_user = ChatChannelsUser.find(:first,
:conditions => {:channel_id => @channel,
:user_id => @user})
if (!@channel_user and (@user.is_a? User) and (action_name != 'archive'))
@channel_user = ChatChannelsUser.create!({:channel => @channel, :user => @user})
end
true
end
def user_say_in_channel(user, channel, say)
say = sanitize(say)
#say = say.gsub(":)", "<img src='../images/emoticons/smiley.png' \/>")
ChatMessage.create(:channel => channel, :content => say, :sender => user)
end
def user_action_in_channel(user, channel, say)
ChatMessage.create(:channel => channel, :content => sanitize(say), :sender => user, :level => 'action')
end
def user_joins_channel(user, channel)
ChatMessage.create(:channel => channel, :sender => user, :content => I18n.t(:joins_the_chatroom), :level => 'sys')
end
def user_leaves_channel(user, channel)
ChatMessage.create(:channel => channel, :sender => user, :content => I18n.t(:left_the_chatroom), :level => 'sys')
end
def sanitize(say)
# we'll use GreenCloth to process the say string ---
# this makes links clickable, and allows inline images,
# and can easily be extended to use smilies, etc...
#
# the only trick is that GreenCloth returns the text wrapped
# in a paragraph block (<p> stuff </p>), and things will
# look funny if we don't strip that off
say = GreenCloth.new(say).to_html
say.gsub! /\A<p>(.+)<\/p>\Z/m, '\1'
return say
end
def breadcrumbs
add_context 'chat', '/chat'
add_context @channel.name, url_for(:controller => 'chat', :action => 'channel', :id => @channel.name) if @channel
@active_tab = :chat
end
end
|
class CrudController < ApplicationController
before_filter :setup, except: :autocomplete
def index
authorize! :read, @model if respond_to?(:current_usuario)
if params[:scope].present?
@q = @model.send(params[:scope]).search(params[:q])
else
@q = @model.search(params[:q])
end
if @q.sorts.empty?
if "#{@crud_helper.order_field}".include?("desc") or "#{@crud_helper.order_field}".include?("asc")
@q.sorts = "#{@crud_helper.order_field}"
else
@q.sorts = "#{@crud_helper.order_field} asc"
end
end
if respond_to?(:current_usuario)
@records = @q.result(distinct: true).accessible_by(current_ability, :read).page(params[:page]).per(@crud_helper.per_page)
else
@records = @q.result(distinct: true).page(params[:page]).per(@crud_helper.per_page)
end
@titulo = @model.name.pluralize
render partial: 'records' if request.respond_to?(:wiselinks_partial?) && request.wiselinks_partial?
end
def setup
@model = Module.const_get(params[:model].camelize)
@crud_helper = Module.const_get("#{params[:model]}_crud".camelize)
end
def new
authorize! :create, @model if respond_to?(:current_usuario)
@record = @model.new
end
def edit
authorize! :edit, @model if respond_to?(:current_usuario)
@record = @model.find(params[:id])
end
def show
authorize! :read, @model if respond_to?(:current_usuario)
@record = @model.find(params[:id])
end
def action
authorize! :create_or_update, @model if respond_to?(:current_usuario)
@record = @model.find(params[:id])
if @model.method_defined?(params[:acao])
if @record.send(params[:acao])
flash.now[:success] = "Ação #{params[:acao]} efetuada com sucesso."
else
flash.now[:error] = "Erro ao tentar executar a ação #{params[:acao]}."
end
index
else
@titulo = @record.to_s
@texto = params[:acao]
render partial: "/#{@model.name.underscore.pluralize}/#{params[:acao]}" if request.respond_to?(:wiselinks_partial?) && request.wiselinks_partial?
end
end
def create
authorize! :create, @model if respond_to?(:current_usuario)
@saved = false
if params[:id]
@record = @model.find(params[:id])
@saved = @record.update(params_permitt)
else
@record = @model.new(params_permitt)
@saved = @record.save
end
respond_to do |format|
if @saved
flash[:success] = params[:id].present? ? "Cadastro alterado com sucesso." : "Cadastro efetuado com sucesso."
format.html { redirect_to "/crud/#{@model.name.underscore}" }
unless params[:render] == 'modal'
format.js { render action: :index }
else
format.js
end
else
action = (params[:id]) ? :edit : :new
format.html { render action: action }
format.js
end
end
end
def destroy
authorize! :destroy, @model if respond_to?(:current_usuario)
@record = @model.find(params[:id])
if @record.destroy
respond_to do |format|
flash[:success] = "Cadastro removido com sucesso."
format.html { redirect_to "/crud/#{@model.name.underscore}" }
format.js { render action: :index }
end
else
respond_to do |format|
flash[:error] = @record.errors.full_messages.join(", ")
format.html { redirect_to "/crud/#{@model.name.underscore}" }
format.js { render action: :index }
end
end
end
def query
authorize! :read, @model if respond_to?(:current_usuario)
@resource = Module.const_get(params[:model].classify)
@q = @resource.search(params[:q])
@q.sorts = 'updated_at desc' if @q.sorts.empty?
if respond_to?(:current_usuario)
results = @q.result(distinct: true).accessible_by(current_ability).page(params[:page])
else
results = @q.result(distinct: true).page(params[:page])
end
instance_variable_set("@#{params[:var]}", results)
if request.respond_to?(:wiselinks_partial?) && request.wiselinks_partial?
render :partial => params[:partial]
else
render :index, controller: request[:controller]
end
end
def autocomplete
@model = Module.const_get(params[:model].camelize)
authorize! :read, @model if respond_to?(:current_usuario)
parametros = {}
parametros["#{params[:campo]}_#{params[:tipo]}"] = params[:term]
@q = @model.search(parametros)
@q.sorts = 'updated_at desc' if @q.sorts.empty?
if respond_to?(:current_usuario)
results = @q.result(distinct: true).accessible_by(current_ability).page(params[:page])
else
results = @q.result(distinct: true).page(params[:page])
end
method_label = params[:label]
render json: results.map {|result| {id: result.id, label: result.send(method_label), value: result.send(method_label)} }
end
private
def params_permitt
params.require(@model.name.underscore.to_sym).permit(fields_model)
end
def fields_model
fields = []
@crud_helper.form_fields.each do |field|
if @model.reflect_on_association(field[:attribute])
if @model.reflect_on_association(field[:attribute]).macro == :belongs_to
fields << @model.reflect_on_association(field[:attribute]).foreign_key
else
fields << {"#{field[:attribute].to_s.singularize}_ids".to_sym => []}
end
elsif @model.columns_hash[field[:attribute].to_s]
fields << field[:attribute]
end
end
@crud_helper.form_groups.each do |key, groups|
chave = "#{key}_attributes"
group = {chave => [:id, :_destroy]}
groups.each do |field|
modelo = @model.reflect_on_association(key.to_s).class_name.constantize
if modelo.reflect_on_association(field[:attribute])
if modelo.reflect_on_association(field[:attribute]).macro == :belongs_to
group[chave] << "#{field[:attribute]}_id".to_sym
else
group[chave] << {"#{field[:attribute].to_s.singularize}_ids".to_sym => []}
end
elsif (modelo.columns_hash[field[:attribute].to_s] || (modelo.respond_to?(:params_permitt) && modelo.params_permitt.include?(field[:attribute].to_sym)))
group[chave] << field[:attribute]
end
end
fields << group
end
if @model.respond_to?(:params_permitt)
@model.params_permitt.each do |field|
fields << field
end
end
fields
end
end
fix permissao grupo formularios
class CrudController < ApplicationController
before_filter :setup, except: :autocomplete
def index
authorize! :read, @model if respond_to?(:current_usuario)
if params[:scope].present?
@q = @model.send(params[:scope]).search(params[:q])
else
@q = @model.search(params[:q])
end
if @q.sorts.empty?
if "#{@crud_helper.order_field}".include?("desc") or "#{@crud_helper.order_field}".include?("asc")
@q.sorts = "#{@crud_helper.order_field}"
else
@q.sorts = "#{@crud_helper.order_field} asc"
end
end
if respond_to?(:current_usuario)
@records = @q.result(distinct: true).accessible_by(current_ability, :read).page(params[:page]).per(@crud_helper.per_page)
else
@records = @q.result(distinct: true).page(params[:page]).per(@crud_helper.per_page)
end
@titulo = @model.name.pluralize
render partial: 'records' if request.respond_to?(:wiselinks_partial?) && request.wiselinks_partial?
end
def setup
@model = Module.const_get(params[:model].camelize)
@crud_helper = Module.const_get("#{params[:model]}_crud".camelize)
end
def new
authorize! :create, @model if respond_to?(:current_usuario)
@record = @model.new
end
def edit
authorize! :edit, @model if respond_to?(:current_usuario)
@record = @model.find(params[:id])
end
def show
authorize! :read, @model if respond_to?(:current_usuario)
@record = @model.find(params[:id])
end
def action
authorize! :create_or_update, @model if respond_to?(:current_usuario)
@record = @model.find(params[:id])
if @model.method_defined?(params[:acao])
if @record.send(params[:acao])
flash.now[:success] = "Ação #{params[:acao]} efetuada com sucesso."
else
flash.now[:error] = "Erro ao tentar executar a ação #{params[:acao]}."
end
index
else
@titulo = @record.to_s
@texto = params[:acao]
render partial: "/#{@model.name.underscore.pluralize}/#{params[:acao]}" if request.respond_to?(:wiselinks_partial?) && request.wiselinks_partial?
end
end
def create
authorize! :create, @model if respond_to?(:current_usuario)
@saved = false
if params[:id]
@record = @model.find(params[:id])
@saved = @record.update(params_permitt)
else
@record = @model.new(params_permitt)
@saved = @record.save
end
respond_to do |format|
if @saved
flash[:success] = params[:id].present? ? "Cadastro alterado com sucesso." : "Cadastro efetuado com sucesso."
format.html { redirect_to "/crud/#{@model.name.underscore}" }
unless params[:render] == 'modal'
format.js { render action: :index }
else
format.js
end
else
action = (params[:id]) ? :edit : :new
format.html { render action: action }
format.js
end
end
end
def destroy
authorize! :destroy, @model if respond_to?(:current_usuario)
@record = @model.find(params[:id])
if @record.destroy
respond_to do |format|
flash[:success] = "Cadastro removido com sucesso."
format.html { redirect_to "/crud/#{@model.name.underscore}" }
format.js { render action: :index }
end
else
respond_to do |format|
flash[:error] = @record.errors.full_messages.join(", ")
format.html { redirect_to "/crud/#{@model.name.underscore}" }
format.js { render action: :index }
end
end
end
def query
authorize! :read, @model if respond_to?(:current_usuario)
@resource = Module.const_get(params[:model].classify)
@q = @resource.search(params[:q])
@q.sorts = 'updated_at desc' if @q.sorts.empty?
if respond_to?(:current_usuario)
results = @q.result(distinct: true).accessible_by(current_ability).page(params[:page])
else
results = @q.result(distinct: true).page(params[:page])
end
instance_variable_set("@#{params[:var]}", results)
if request.respond_to?(:wiselinks_partial?) && request.wiselinks_partial?
render :partial => params[:partial]
else
render :index, controller: request[:controller]
end
end
def autocomplete
@model = Module.const_get(params[:model].camelize)
authorize! :read, @model if respond_to?(:current_usuario)
parametros = {}
parametros["#{params[:campo]}_#{params[:tipo]}"] = params[:term]
@q = @model.search(parametros)
@q.sorts = 'updated_at desc' if @q.sorts.empty?
if respond_to?(:current_usuario)
results = @q.result(distinct: true).accessible_by(current_ability).page(params[:page])
else
results = @q.result(distinct: true).page(params[:page])
end
method_label = params[:label]
render json: results.map {|result| {id: result.id, label: result.send(method_label), value: result.send(method_label)} }
end
private
def params_permitt
params.require(@model.name.underscore.to_sym).permit(fields_model)
end
def fields_model
fields = []
@crud_helper.form_fields.each do |field|
if @model.reflect_on_association(field[:attribute])
if @model.reflect_on_association(field[:attribute]).macro == :belongs_to
fields << @model.reflect_on_association(field[:attribute]).foreign_key
else
fields << {"#{field[:attribute].to_s.singularize}_ids".to_sym => []}
end
elsif @model.columns_hash[field[:attribute].to_s]
fields << field[:attribute]
end
end
@crud_helper.form_groups.each do |key, groups|
chave = "#{key}_attributes"
group = {chave => [:id, :_destroy]}
groups[:fields].each do |field|
modelo = @model.reflect_on_association(key.to_s).class_name.constantize
if modelo.reflect_on_association(field[:attribute])
if modelo.reflect_on_association(field[:attribute]).macro == :belongs_to
group[chave] << "#{field[:attribute]}_id".to_sym
else
group[chave] << {"#{field[:attribute].to_s.singularize}_ids".to_sym => []}
end
elsif (modelo.columns_hash[field[:attribute].to_s] || (modelo.respond_to?(:params_permitt) && modelo.params_permitt.include?(field[:attribute].to_sym)))
group[chave] << field[:attribute]
end
end
fields << group
end
if @model.respond_to?(:params_permitt)
@model.params_permitt.each do |field|
fields << field
end
end
fields
end
end |
require 'fileutils'
require 'zip/zip'
class DocsController < ApplicationController
protect_from_forgery :except => [:create]
before_filter :authenticate_user!, :only => [:new, :create, :create_from_upload, :edit, :update, :destroy, :project_delete_doc, :project_delete_all_docs]
before_filter :http_basic_authenticate, :only => :create, :if => Proc.new{|c| c.request.format == 'application/jsonrequest'}
skip_before_filter :authenticate_user!, :verify_authenticity_token, :if => Proc.new{|c| c.request.format == 'application/jsonrequest'}
cache_sweeper :doc_sweeper
autocomplete :doc, :sourcedb
def index
begin
if params[:project_id].present?
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "Could not find the project." unless @project.present?
end
@sourcedb = params[:sourcedb]
page, per = if params[:format] && (params[:format] == "json" || params[:format] == "tsv")
params.delete(:page)
[1, 1000]
else
[params[:page], 10]
end
htexts = nil
@docs = if params[:keywords].present?
project_id = @project.nil? ? nil : @project.id
search_results = Doc.search_docs({body: params[:keywords].strip.downcase, project_id: project_id, sourcedb: @sourcedb, page:page, per:per})
@search_count = search_results.results.total
htexts = search_results.results.map{|r| {text: r.highlight.body}}
search_results.records
else
sort_order = sort_order(Doc)
if params[:randomize]
sort_order = sort_order ? sort_order + ', ' : ''
sort_order += 'random()'
end
if @project.present?
if @sourcedb.present?
if Doc.is_mdoc_sourcedb(@sourcedb)
@project.docs.where(sourcedb: @sourcedb, serial: 0).order(sort_order).simple_paginate(page, per)
else
@project.docs.where(sourcedb: @sourcedb).order(sort_order).simple_paginate(page, per)
end
else
@project.docs.where(serial: 0).order(sort_order).simple_paginate(page, per)
end
else
if @sourcedb.present?
if Doc.is_mdoc_sourcedb(@sourcedb)
Doc.where(sourcedb: @sourcedb, serial: 0).order(sort_order).simple_paginate(page, per)
else
Doc.where(sourcedb: @sourcedb).order(sort_order).simple_paginate(page, per)
end
else
Doc.where(serial: 0).order(sort_order).simple_paginate(page, per)
end
end
end
respond_to do |format|
format.html {
if htexts
htexts = htexts.map{|h| h[:text].first}
@docs = @docs.zip(htexts).each{|d,t| d.body = t}.map{|d,t| d}
end
}
format.json {
hdocs = @docs.map{|d| d.to_list_hash('doc')}
if htexts
hdocs = hdocs.zip(htexts).map{|d| d.reduce(:merge)}
end
render json: hdocs
}
format.tsv {
hdocs = @docs.map{|d| d.to_list_hash('doc')}
if htexts
htexts.each{|h| h[:text] = h[:text].first}
hdocs = hdocs.zip(htexts).map{|d| d.reduce(:merge)}
end
render text: Doc.hash_to_tsv(hdocs)
}
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def records
if params[:project_id]
@project, notice = get_project(params[:project_id])
@new_doc_src = new_project_doc_path
if @project
@docs = @project.docs.order('sourcedb ASC').order('sourceid ASC').order('serial ASC')
else
@docs = nil
end
else
@docs = Doc.order('sourcedb ASC').order('sourceid ASC').order('serial ASC')
@new_doc_src = new_doc_path
end
@docs.each{|doc| doc.set_ascii_body} if (params[:encoding] == 'ascii')
respond_to do |format|
if @docs
format.html { @docs = @docs.page(params[:page]) }
format.json { render json: @docs }
format.txt {
file_name = (@project)? @project.name + ".zip" : "docs.zip"
t = Tempfile.new("pubann-temp-filename-#{Time.now}")
Zip::ZipOutputStream.open(t.path) do |z|
@docs.each do |doc|
title = "%s-%s-%02d-%s" % [doc.sourcedb, doc.sourceid, doc.serial, doc.section]
title.sub!(/\.$/, '')
title.gsub!(' ', '_')
title += ".txt" unless title.end_with?(".txt")
z.put_next_entry(title)
z.print doc.body
end
end
send_file t.path, :type => 'application/zip',
:disposition => 'attachment',
:filename => file_name
t.close
# texts = @docs.collect{|doc| doc.body}
# render text: texts.join("\n----------\n")
}
else
format.html { flash[:notice] = notice }
format.json { head :unprocessable_entity }
format.txt { head :unprocessable_entity }
end
end
end
def sourcedb_index
begin
if params[:project_id].present?
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
end
rescue => e
respond_to do |format|
format.html {redirect_to :back, notice: e.message}
end
end
end
def show
begin
divs = if params[:id].present?
[Doc.find(params[:id])]
else
Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
end
raise "There is no such document." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to doc_sourcedb_sourceid_divs_index_path params}
format.json {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render json: divs.collect{|div| div.to_hash}
}
format.txt {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render text: divs.collect{|div| div.body}.join("\n")
}
end
else
@doc = divs[0]
@doc.set_ascii_body if params[:encoding] == 'ascii'
@content = @doc.body.gsub(/\n/, "<br>")
get_docs_projects
respond_to do |format|
format.html
format.json {render json: @doc.to_hash}
format.txt {render text: @doc.body}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def show_in_project
begin
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "Could not find the project." unless @project.present?
divs = @project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "Could not find the document within this project." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to index_project_sourcedb_sourceid_divs_docs_path(@project.name, params[:sourcedb], params[:sourceid])}
format.json {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render json: divs.collect{|div| div.body}
}
format.txt {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render text: divs.collect{|div| div.body}.join("\n")
}
end
else
@doc = divs[0]
@doc.set_ascii_body if (params[:encoding] == 'ascii')
@content = @doc.body.gsub(/\n/, "<br>")
respond_to do |format|
format.html
format.json {render json: @doc.to_hash}
format.txt {render text: @doc.body}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render status: :unprocessable_entity}
end
end
end
def open
params[:sourceid].strip!
begin
if params[:project_id].present?
project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "Could not find the project." unless project.present?
divs = project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "Could not find the document within this project." unless divs.present?
respond_to do |format|
format.html {redirect_to show_project_sourcedb_sourceid_docs_path(params[:project_id], params[:sourcedb], params[:sourceid])}
end
else
divs = Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "Could not find the document within PubAnnotation." unless divs.present?
respond_to do |format|
format.html {redirect_to doc_sourcedb_sourceid_show_path(params[:sourcedb], params[:sourceid])}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to :back, notice: e.message}
end
end
end
# GET /docs/new
# GET /docs/new.json
def new
@doc = Doc.new
begin
@project = get_project2(params[:project_id])
rescue => e
notice = e.message
end
respond_to do |format|
format.html # new.html.erb
format.json {render json: @doc.to_hash}
end
end
# POST /docs
# POST /docs.json
# Creation of document is only allowed for single division documents.
def create
begin
raise ArgumentError, "project id has to be specified." unless params[:project_id].present?
@project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project does not exist, or you are not authorized to make a change to the project.\n" unless @project.present?
doc_hash = if params[:doc].present? && params[:commit].present?
params[:doc]
else
text = if params[:text]
params[:text]
elsif request.content_type =~ /text/
request.body.read
end
raise "Could not find text." unless text.present?
_doc = {
source: params[:source],
sourcedb: params[:sourcedb] || '',
sourceid: params[:sourceid],
section: params[:section],
body: text
}
_doc[:divisions] = params[:divisions] if params[:divisions].present?
_doc[:typesettings] = params[:typesettings] if params[:typesettings].present?
_doc
end
doc_hash = Doc.hdoc_normalize!(doc_hash, current_user, current_user.root?)
docs_saved, messages = Doc.store_hdocs([doc_hash])
raise IOError, "Could not create the document: #{messages.join("\n")}" if messages.present?
@doc = docs_saved.first
@doc.projects << @project
expire_fragment("sourcedb_counts_#{@project.name}")
expire_fragment("count_docs_#{@project.name}")
expire_fragment("count_#{@doc.sourcedb}_#{@project.name}")
respond_to do |format|
format.html { redirect_to show_project_sourcedb_sourceid_docs_path(@project.name, doc_hash[:sourcedb], doc_hash[:sourceid]), notice: t('controllers.shared.successfully_created', :model => t('activerecord.models.doc')) }
format.json { render json: @doc.to_hash, status: :created, location: @doc }
end
rescue => e
respond_to do |format|
format.html { redirect_to new_project_doc_path(@project.name), notice: e.message }
format.json { render json: {message: e.message}, status: :unprocessable_entity }
end
end
end
def create_from_upload
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise ArgumentError, "Could not find the project." unless project.present?
file = params[:upfile]
filename = file.original_filename
ext = File.extname(filename).downcase
ext = '.tar.gz' if ext == '.gz' && filename.end_with?('.tar.gz')
raise ArgumentError, "Unknown file type: '#{ext}'." unless ['.tgz', '.tar.gz', '.json', '.txt'].include?(ext)
options = {
mode: params[:mode].present? ? params[:mode].to_sym : :update,
root: current_user.root?
}
dirpath = File.join('tmp/uploads', "#{params[:project_id]}-#{Time.now.to_s[0..18].gsub(/[ :]/, '-')}")
FileUtils.mkdir_p dirpath
FileUtils.mv file.path, File.join(dirpath, filename)
if ['.json', '.txt'].include?(ext) && file.size < 100.kilobytes
job = UploadDocsJob.new(dirpath, project, options)
res = job.perform()
notice = "Documents are successfully uploaded."
else
raise "Up to 10 jobs can be registered per a project. Please clean your jobs page." unless project.jobs.count < 10
priority = project.jobs.unfinished.count
# job = UploadDocsJob.new(dirpath, project, options)
# job.perform()
delayed_job = Delayed::Job.enqueue UploadDocsJob.new(dirpath, project, options), priority: priority, queue: :upload
task_name = "Upload documents: #{filename}"
Job.create({name:task_name, project_id:project.id, delayed_job_id:delayed_job.id})
notice = "The task, '#{task_name}', is created."
end
rescue => e
notice = e.message
end
respond_to do |format|
format.html {redirect_to :back, notice: notice}
format.json {}
end
end
# GET /docs/1/edit
def edit
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
divs = if params.has_key? :id
[Doc.find(params[:id])]
else
Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
end
raise "There is no such document" unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to :back}
end
else
@doc = divs[0]
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : home_path), notice: e.message}
end
end
end
# PUT /docs/1
# PUT /docs/1.json
def update
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
params[:doc][:body].gsub!(/\r\n/, "\n")
@doc = Doc.find(params[:id])
respond_to do |format|
if @doc.update_attributes(params[:doc])
format.html { redirect_to @doc, notice: t('controllers.shared.successfully_updated', :model => t('activerecord.models.doc')) }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @doc.errors, status: :unprocessable_entity }
end
end
end
# add new docs to a project
def add_from_upload
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project does not exist, or you are not authorized to make a change to the project.\n" unless project.present?
raise ArgumentError, "sourcedb is not specified." unless params["sourcedb"].present?
sourcedb = params["sourcedb"]
filename = params[:upfile].original_filename
ext = File.extname(filename)
raise ArgumentError, "Unknown file type: '#{ext}'." unless ['.txt'].include?(ext)
raise "Up to 10 jobs can be registered per a project. Please clean your jobs page." unless project.jobs.count < 10
filepath = File.join('tmp', "add-docs-to-#{params[:project_id]}-#{Time.now.to_s[0..18].gsub(/[ :]/, '-')}#{ext}")
FileUtils.mv params[:upfile].path, filepath
# job = AddDocsToProjectFromUploadJob.new(sourcedb, filepath, project)
# job.perform()
priority = project.jobs.unfinished.count
delayed_job = Delayed::Job.enqueue AddDocsToProjectFromUploadJob.new(sourcedb, filepath, project), priority: priority, queue: :general
job = Job.create({name:'Add docs to project from upload', project_id:project.id, delayed_job_id:delayed_job.id})
message = "The task, 'Add docs to project from upload', is created."
respond_to do |format|
format.html {redirect_to :back, notice: message}
format.json {render json: {message: message, task_location: project_job_url(project.name, job.id, format: :json)}, status: :ok}
end
rescue => e
respond_to do |format|
format.html {redirect_to :back, notice: e.message}
format.json {render json: {message: e.message}, status: :unprocessable_entity}
end
end
end
# add new docs to a project
def add
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project does not exist, or you are not authorized to make a change to the project.\n" unless project.present?
# get the docspecs list
docspecs = if params["_json"] && params["_json"].class == Array
params["_json"].collect{|d| d.symbolize_keys}
elsif params["sourcedb"].present? && params["sourceid"].present?
[{sourcedb:params["sourcedb"], sourceid:params["sourceid"]}]
elsif params[:ids].present? && params[:sourcedb].present?
params[:ids].strip.split(/[ ,"':|\t\n\r]+/).collect{|id| id.strip}.collect{|id| {sourcedb:params[:sourcedb], sourceid:id}}
else
[]
end
raise ArgumentError, "no valid document specification found." if docspecs.empty?
docspecs.each{|d| d[:sourceid].sub!(/^(PMC|pmc)/, '')}
docspecs.uniq!
if docspecs.length == 1
docspec = docspecs.first
begin
divs = project.add_doc(docspec[:sourcedb], docspec[:sourceid])
raise ArgumentError, "The document already exists." if divs.nil?
expire_fragment("sourcedb_counts_#{project.name}")
expire_fragment("count_docs_#{project.name}")
expire_fragment("count_#{docspec[:sourcedb]}_#{project.name}")
message = "#{docspec[:sourcedb]}:#{docspec[:sourceid]} - added."
rescue => e
message = "#{docspec[:sourcedb]}:#{docspec[:sourceid]} - #{e.message}"
end
else
# delayed_job = AddDocsToProjectJob.new(docspecs, project)
# delayed_job.perform()
priority = project.jobs.unfinished.count
delayed_job = Delayed::Job.enqueue AddDocsToProjectJob.new(docspecs, project), priority: priority, queue: :general
Job.create({name:'Add docs to project', project_id:project.id, delayed_job_id:delayed_job.id})
message = "The task, 'add documents to the project', is created."
end
rescue => e
message = e.message
end
respond_to do |format|
format.html {redirect_to :back, notice: message}
format.json {render json:{message:message}}
end
end
def import
message = begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project (#{params[:project_id]}) does not exist, or you are not authorized to make a change to it.\n" unless project.present?
source_project = Project.find_by_name(params["select_project"])
raise ArgumentError, "The project (#{params["select_project"]}) does not exist, or you are not authorized to access it.\n" unless source_project.present?
raise ArgumentError, "You cannot import documents from itself." if source_project == project
docids = source_project.docs.pluck(:id) - project.docs.pluck(:id)
if docids.empty?
"There is no document to import from the project, '#{params["select_project"]}'."
else
num_source_docs = source_project.docs.count
num_skip = num_source_docs - docids.length
docids_file = Tempfile.new("docids")
docids_file.puts docids
docids_file.close
priority = project.jobs.unfinished.count
delayed_job = Delayed::Job.enqueue ImportDocsJob.new(docids_file.path, project), priority: priority, queue: :general
Job.create({name:'Import docs to project', project_id:project.id, delayed_job_id:delayed_job.id})
m = ""
m += "#{num_skip} docs were skipped due to duplication." if num_skip > 0
m += "The task, 'import documents to the project', is created."
end
rescue => e
e.message
end
respond_to do |format|
format.html {redirect_to :back, notice: message}
format.json {render json:{message:message}}
end
end
def uptodate
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
divs = params[:sourceid].present? ? Doc.where(sourcedb:params[:sourcedb], sourceid:params[:sourceid]).order(:serial) : nil
raise ArgumentError, "There is no such document." if params[:sourceid].present? && !divs.present?
p = {
size_ngram: params[:size_ngram],
size_window: params[:size_window],
threshold: params[:threshold]
}.compact
Doc.uptodate(divs)
message = "The document #{divs[0].descriptor} is successfully updated."
redirect_to doc_sourcedb_sourceid_show_path(params[:sourcedb], params[:sourceid]), notice: message
rescue => e
redirect_to :back, notice: e.message
end
# DELETE /docs/sourcedb/:sourcedb/sourceid/:sourceid
def delete
raise SecurityError, "Not authorized" unless current_user && current_user.root? == true
divs = Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document." unless divs.present?
sourcedb = divs.first.sourcedb
divs.each{|div| div.destroy}
redirect_to doc_sourcedb_index_path(sourcedb)
end
# DELETE /docs/1
# DELETE /docs/1.json
def destroy
begin
doc = Doc.find(params[:id])
if params[:project_id].present?
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "There is no such project in your management." unless project.present?
project.docs.delete(doc)
expire_fragment("sourcedb_counts_#{project.name}")
expire_fragment("count_docs_#{project.name}")
expire_fragment("count_#{doc.sourcedb}_#{project.name}")
redirect_path = records_project_docs_path(params[:project_id])
else
raise SecurityError, "Not authorized" unless current_user && current_user.root? == true
doc.destroy
redirect_path = home_path
end
message = 'the document is deleted from the project.'
respond_to do |format|
format.html { redirect_to redirect_path }
format.json { render json: {message: message} }
format.txt { render text: message }
end
rescue => e
respond_to do |format|
format.html { redirect_to redirect_path, notice: e.message }
format.json { render json: {message: e.message}, status: :unprocessable_entity }
format.txt { render text: e.message, status: :unprocessable_entity }
end
end
end
def project_delete_doc
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project does not exist, or you are not authorized to make a change to the project.\n" unless project.present?
divs = project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "The document does not exist in the project.\n" unless divs.present?
divs.each{|div| project.delete_doc(div)}
expire_fragment("sourcedb_counts_#{project.name}")
expire_fragment("count_docs_#{project.name}")
expire_fragment("count_#{params[:sourcedb]}_#{project.name}")
message = "the document is deleted from the project.\n"
respond_to do |format|
format.html { redirect_to project_docs_path(project.name), notice:message }
format.json { render json: {message: message} }
format.txt { render text: message }
end
rescue => e
respond_to do |format|
format.html { redirect_to project_docs_path(project.name), notice:e.message }
format.json { render json: {message: e.message}, status: :unprocessable_entity }
format.txt { render text: e.message, status: :unprocessable_entity }
end
end
end
def store_span_rdf
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
projects = Project.for_index
docids = projects.inject([]){|col, p| (col + p.docs.pluck(:id))}.uniq
system = Project.find_by_name('system-maintenance')
delayed_job = Delayed::Job.enqueue StoreRdfizedSpansJob.new(system, docids, Pubann::Application.config.rdfizer_spans), queue: :general
Job.create({name:"Store RDFized spans for selected projects", project_id:system.id, delayed_job_id:delayed_job.id})
rescue => e
flash[:notice] = e.message
end
redirect_to project_path('system-maintenance')
end
def update_numbers
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
system = Project.find_by_name('system-maintenance')
delayed_job = Delayed::Job.enqueue UpdateAnnotationNumbersJob.new(nil), queue: :general
Job.create({name:"Update annotation numbers of each document", project_id:system.id, delayed_job_id:delayed_job.id})
result = {message: "The task, 'update annotation numbers of each document', created."}
redirect_to project_path('system-maintenance')
rescue => e
flash[:notice] = e.message
redirect_to home_path
end
end
# def autocomplete_sourcedb
# render :json => Doc.where(['LOWER(sourcedb) like ?', "%#{params[:term].downcase}%"]).collect{|doc| doc.sourcedb}.uniq
# end
end
REMOVED 'serial'-related parts (incomplete)
require 'fileutils'
require 'zip/zip'
class DocsController < ApplicationController
protect_from_forgery :except => [:create]
before_filter :authenticate_user!, :only => [:new, :create, :create_from_upload, :edit, :update, :destroy, :project_delete_doc, :project_delete_all_docs]
before_filter :http_basic_authenticate, :only => :create, :if => Proc.new{|c| c.request.format == 'application/jsonrequest'}
skip_before_filter :authenticate_user!, :verify_authenticity_token, :if => Proc.new{|c| c.request.format == 'application/jsonrequest'}
cache_sweeper :doc_sweeper
autocomplete :doc, :sourcedb
def index
begin
if params[:project_id].present?
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "Could not find the project." unless @project.present?
end
@sourcedb = params[:sourcedb]
page, per = if params[:format] && (params[:format] == "json" || params[:format] == "tsv")
params.delete(:page)
[1, 1000]
else
[params[:page], 10]
end
htexts = nil
@docs = if params[:keywords].present?
project_id = @project.nil? ? nil : @project.id
search_results = Doc.search_docs({body: params[:keywords].strip.downcase, project_id: project_id, sourcedb: @sourcedb, page:page, per:per})
@search_count = search_results.results.total
htexts = search_results.results.map{|r| {text: r.highlight.body}}
search_results.records
else
sort_order = sort_order(Doc)
if params[:randomize]
sort_order = sort_order ? sort_order + ', ' : ''
sort_order += 'random()'
end
if @project.present?
if @sourcedb.present?
@project.docs.where(sourcedb: @sourcedb).order(sort_order).simple_paginate(page, per)
else
@project.docs.order(sort_order).simple_paginate(page, per)
end
else
if @sourcedb.present?
Doc.where(sourcedb: @sourcedb).order(sort_order).simple_paginate(page, per)
else
Doc.order(sort_order).simple_paginate(page, per)
end
end
end
respond_to do |format|
format.html {
if htexts
htexts = htexts.map{|h| h[:text].first}
@docs = @docs.zip(htexts).each{|d,t| d.body = t}.map{|d,t| d}
end
}
format.json {
hdocs = @docs.map{|d| d.to_list_hash('doc')}
if htexts
hdocs = hdocs.zip(htexts).map{|d| d.reduce(:merge)}
end
render json: hdocs
}
format.tsv {
hdocs = @docs.map{|d| d.to_list_hash('doc')}
if htexts
htexts.each{|h| h[:text] = h[:text].first}
hdocs = hdocs.zip(htexts).map{|d| d.reduce(:merge)}
end
render text: Doc.hash_to_tsv(hdocs)
}
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def records
if params[:project_id]
@project, notice = get_project(params[:project_id])
@new_doc_src = new_project_doc_path
if @project
@docs = @project.docs.order('sourcedb ASC').order('sourceid ASC').order('serial ASC')
else
@docs = nil
end
else
@docs = Doc.order('sourcedb ASC').order('sourceid ASC').order('serial ASC')
@new_doc_src = new_doc_path
end
@docs.each{|doc| doc.set_ascii_body} if (params[:encoding] == 'ascii')
respond_to do |format|
if @docs
format.html { @docs = @docs.page(params[:page]) }
format.json { render json: @docs }
format.txt {
file_name = (@project)? @project.name + ".zip" : "docs.zip"
t = Tempfile.new("pubann-temp-filename-#{Time.now}")
Zip::ZipOutputStream.open(t.path) do |z|
@docs.each do |doc|
title = "%s-%s-%02d-%s" % [doc.sourcedb, doc.sourceid, doc.serial, doc.section]
title.sub!(/\.$/, '')
title.gsub!(' ', '_')
title += ".txt" unless title.end_with?(".txt")
z.put_next_entry(title)
z.print doc.body
end
end
send_file t.path, :type => 'application/zip',
:disposition => 'attachment',
:filename => file_name
t.close
# texts = @docs.collect{|doc| doc.body}
# render text: texts.join("\n----------\n")
}
else
format.html { flash[:notice] = notice }
format.json { head :unprocessable_entity }
format.txt { head :unprocessable_entity }
end
end
end
def sourcedb_index
begin
if params[:project_id].present?
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "There is no such project." unless @project.present?
end
rescue => e
respond_to do |format|
format.html {redirect_to :back, notice: e.message}
end
end
end
def show
begin
divs = if params[:id].present?
[Doc.find(params[:id])]
else
Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
end
raise "There is no such document." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to doc_sourcedb_sourceid_divs_index_path params}
format.json {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render json: divs.collect{|div| div.to_hash}
}
format.txt {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render text: divs.collect{|div| div.body}.join("\n")
}
end
else
@doc = divs[0]
@doc.set_ascii_body if params[:encoding] == 'ascii'
@content = @doc.body.gsub(/\n/, "<br>")
get_docs_projects
respond_to do |format|
format.html
format.json {render json: @doc.to_hash}
format.txt {render text: @doc.body}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render text: message, status: :unprocessable_entity}
end
end
end
def show_in_project
begin
@project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "Could not find the project." unless @project.present?
divs = @project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "Could not find the document within this project." unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to index_project_sourcedb_sourceid_divs_docs_path(@project.name, params[:sourcedb], params[:sourceid])}
format.json {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render json: divs.collect{|div| div.body}
}
format.txt {
divs.each{|div| div.set_ascii_body} if params[:encoding] == 'ascii'
render text: divs.collect{|div| div.body}.join("\n")
}
end
else
@doc = divs[0]
@doc.set_ascii_body if (params[:encoding] == 'ascii')
@content = @doc.body.gsub(/\n/, "<br>")
respond_to do |format|
format.html
format.json {render json: @doc.to_hash}
format.txt {render text: @doc.body}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : home_path), notice: e.message}
format.json {render json: {notice:e.message}, status: :unprocessable_entity}
format.txt {render status: :unprocessable_entity}
end
end
end
def open
params[:sourceid].strip!
begin
if params[:project_id].present?
project = Project.accessible(current_user).find_by_name(params[:project_id])
raise "Could not find the project." unless project.present?
divs = project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "Could not find the document within this project." unless divs.present?
respond_to do |format|
format.html {redirect_to show_project_sourcedb_sourceid_docs_path(params[:project_id], params[:sourcedb], params[:sourceid])}
end
else
divs = Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "Could not find the document within PubAnnotation." unless divs.present?
respond_to do |format|
format.html {redirect_to doc_sourcedb_sourceid_show_path(params[:sourcedb], params[:sourceid])}
end
end
rescue => e
respond_to do |format|
format.html {redirect_to :back, notice: e.message}
end
end
end
# GET /docs/new
# GET /docs/new.json
def new
@doc = Doc.new
begin
@project = get_project2(params[:project_id])
rescue => e
notice = e.message
end
respond_to do |format|
format.html # new.html.erb
format.json {render json: @doc.to_hash}
end
end
# POST /docs
# POST /docs.json
# Creation of document is only allowed for single division documents.
def create
begin
raise ArgumentError, "project id has to be specified." unless params[:project_id].present?
@project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project does not exist, or you are not authorized to make a change to the project.\n" unless @project.present?
doc_hash = if params[:doc].present? && params[:commit].present?
params[:doc]
else
text = if params[:text]
params[:text]
elsif request.content_type =~ /text/
request.body.read
end
raise "Could not find text." unless text.present?
_doc = {
source: params[:source],
sourcedb: params[:sourcedb] || '',
sourceid: params[:sourceid],
section: params[:section],
body: text
}
_doc[:divisions] = params[:divisions] if params[:divisions].present?
_doc[:typesettings] = params[:typesettings] if params[:typesettings].present?
_doc
end
doc_hash = Doc.hdoc_normalize!(doc_hash, current_user, current_user.root?)
docs_saved, messages = Doc.store_hdocs([doc_hash])
raise IOError, "Could not create the document: #{messages.join("\n")}" if messages.present?
@doc = docs_saved.first
@doc.projects << @project
expire_fragment("sourcedb_counts_#{@project.name}")
expire_fragment("count_docs_#{@project.name}")
expire_fragment("count_#{@doc.sourcedb}_#{@project.name}")
respond_to do |format|
format.html { redirect_to show_project_sourcedb_sourceid_docs_path(@project.name, doc_hash[:sourcedb], doc_hash[:sourceid]), notice: t('controllers.shared.successfully_created', :model => t('activerecord.models.doc')) }
format.json { render json: @doc.to_hash, status: :created, location: @doc }
end
rescue => e
respond_to do |format|
format.html { redirect_to new_project_doc_path(@project.name), notice: e.message }
format.json { render json: {message: e.message}, status: :unprocessable_entity }
end
end
end
def create_from_upload
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise ArgumentError, "Could not find the project." unless project.present?
file = params[:upfile]
filename = file.original_filename
ext = File.extname(filename).downcase
ext = '.tar.gz' if ext == '.gz' && filename.end_with?('.tar.gz')
raise ArgumentError, "Unknown file type: '#{ext}'." unless ['.tgz', '.tar.gz', '.json', '.txt'].include?(ext)
options = {
mode: params[:mode].present? ? params[:mode].to_sym : :update,
root: current_user.root?
}
dirpath = File.join('tmp/uploads', "#{params[:project_id]}-#{Time.now.to_s[0..18].gsub(/[ :]/, '-')}")
FileUtils.mkdir_p dirpath
FileUtils.mv file.path, File.join(dirpath, filename)
if ['.json', '.txt'].include?(ext) && file.size < 100.kilobytes
job = UploadDocsJob.new(dirpath, project, options)
res = job.perform()
notice = "Documents are successfully uploaded."
else
raise "Up to 10 jobs can be registered per a project. Please clean your jobs page." unless project.jobs.count < 10
priority = project.jobs.unfinished.count
# job = UploadDocsJob.new(dirpath, project, options)
# job.perform()
delayed_job = Delayed::Job.enqueue UploadDocsJob.new(dirpath, project, options), priority: priority, queue: :upload
task_name = "Upload documents: #{filename}"
Job.create({name:task_name, project_id:project.id, delayed_job_id:delayed_job.id})
notice = "The task, '#{task_name}', is created."
end
rescue => e
notice = e.message
end
respond_to do |format|
format.html {redirect_to :back, notice: notice}
format.json {}
end
end
# GET /docs/1/edit
def edit
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
divs = if params.has_key? :id
[Doc.find(params[:id])]
else
Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
end
raise "There is no such document" unless divs.present?
if divs.length > 1
respond_to do |format|
format.html {redirect_to :back}
end
else
@doc = divs[0]
end
rescue => e
respond_to do |format|
format.html {redirect_to (@project.present? ? project_docs_path(@project.name) : home_path), notice: e.message}
end
end
end
# PUT /docs/1
# PUT /docs/1.json
def update
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
params[:doc][:body].gsub!(/\r\n/, "\n")
@doc = Doc.find(params[:id])
respond_to do |format|
if @doc.update_attributes(params[:doc])
format.html { redirect_to @doc, notice: t('controllers.shared.successfully_updated', :model => t('activerecord.models.doc')) }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @doc.errors, status: :unprocessable_entity }
end
end
end
# add new docs to a project
def add_from_upload
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project does not exist, or you are not authorized to make a change to the project.\n" unless project.present?
raise ArgumentError, "sourcedb is not specified." unless params["sourcedb"].present?
sourcedb = params["sourcedb"]
filename = params[:upfile].original_filename
ext = File.extname(filename)
raise ArgumentError, "Unknown file type: '#{ext}'." unless ['.txt'].include?(ext)
raise "Up to 10 jobs can be registered per a project. Please clean your jobs page." unless project.jobs.count < 10
filepath = File.join('tmp', "add-docs-to-#{params[:project_id]}-#{Time.now.to_s[0..18].gsub(/[ :]/, '-')}#{ext}")
FileUtils.mv params[:upfile].path, filepath
# job = AddDocsToProjectFromUploadJob.new(sourcedb, filepath, project)
# job.perform()
priority = project.jobs.unfinished.count
delayed_job = Delayed::Job.enqueue AddDocsToProjectFromUploadJob.new(sourcedb, filepath, project), priority: priority, queue: :general
job = Job.create({name:'Add docs to project from upload', project_id:project.id, delayed_job_id:delayed_job.id})
message = "The task, 'Add docs to project from upload', is created."
respond_to do |format|
format.html {redirect_to :back, notice: message}
format.json {render json: {message: message, task_location: project_job_url(project.name, job.id, format: :json)}, status: :ok}
end
rescue => e
respond_to do |format|
format.html {redirect_to :back, notice: e.message}
format.json {render json: {message: e.message}, status: :unprocessable_entity}
end
end
end
# add new docs to a project
def add
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project does not exist, or you are not authorized to make a change to the project.\n" unless project.present?
# get the docspecs list
docspecs = if params["_json"] && params["_json"].class == Array
params["_json"].collect{|d| d.symbolize_keys}
elsif params["sourcedb"].present? && params["sourceid"].present?
[{sourcedb:params["sourcedb"], sourceid:params["sourceid"]}]
elsif params[:ids].present? && params[:sourcedb].present?
params[:ids].strip.split(/[ ,"':|\t\n\r]+/).collect{|id| id.strip}.collect{|id| {sourcedb:params[:sourcedb], sourceid:id}}
else
[]
end
raise ArgumentError, "no valid document specification found." if docspecs.empty?
docspecs.each{|d| d[:sourceid].sub!(/^(PMC|pmc)/, '')}
docspecs.uniq!
if docspecs.length == 1
docspec = docspecs.first
begin
divs = project.add_doc(docspec[:sourcedb], docspec[:sourceid])
raise ArgumentError, "The document already exists." if divs.nil?
expire_fragment("sourcedb_counts_#{project.name}")
expire_fragment("count_docs_#{project.name}")
expire_fragment("count_#{docspec[:sourcedb]}_#{project.name}")
message = "#{docspec[:sourcedb]}:#{docspec[:sourceid]} - added."
rescue => e
message = "#{docspec[:sourcedb]}:#{docspec[:sourceid]} - #{e.message}"
end
else
# delayed_job = AddDocsToProjectJob.new(docspecs, project)
# delayed_job.perform()
priority = project.jobs.unfinished.count
delayed_job = Delayed::Job.enqueue AddDocsToProjectJob.new(docspecs, project), priority: priority, queue: :general
Job.create({name:'Add docs to project', project_id:project.id, delayed_job_id:delayed_job.id})
message = "The task, 'add documents to the project', is created."
end
rescue => e
message = e.message
end
respond_to do |format|
format.html {redirect_to :back, notice: message}
format.json {render json:{message:message}}
end
end
def import
message = begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project (#{params[:project_id]}) does not exist, or you are not authorized to make a change to it.\n" unless project.present?
source_project = Project.find_by_name(params["select_project"])
raise ArgumentError, "The project (#{params["select_project"]}) does not exist, or you are not authorized to access it.\n" unless source_project.present?
raise ArgumentError, "You cannot import documents from itself." if source_project == project
docids = source_project.docs.pluck(:id) - project.docs.pluck(:id)
if docids.empty?
"There is no document to import from the project, '#{params["select_project"]}'."
else
num_source_docs = source_project.docs.count
num_skip = num_source_docs - docids.length
docids_file = Tempfile.new("docids")
docids_file.puts docids
docids_file.close
priority = project.jobs.unfinished.count
delayed_job = Delayed::Job.enqueue ImportDocsJob.new(docids_file.path, project), priority: priority, queue: :general
Job.create({name:'Import docs to project', project_id:project.id, delayed_job_id:delayed_job.id})
m = ""
m += "#{num_skip} docs were skipped due to duplication." if num_skip > 0
m += "The task, 'import documents to the project', is created."
end
rescue => e
e.message
end
respond_to do |format|
format.html {redirect_to :back, notice: message}
format.json {render json:{message:message}}
end
end
def uptodate
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
divs = params[:sourceid].present? ? Doc.where(sourcedb:params[:sourcedb], sourceid:params[:sourceid]).order(:serial) : nil
raise ArgumentError, "There is no such document." if params[:sourceid].present? && !divs.present?
p = {
size_ngram: params[:size_ngram],
size_window: params[:size_window],
threshold: params[:threshold]
}.compact
Doc.uptodate(divs)
message = "The document #{divs[0].descriptor} is successfully updated."
redirect_to doc_sourcedb_sourceid_show_path(params[:sourcedb], params[:sourceid]), notice: message
rescue => e
redirect_to :back, notice: e.message
end
# DELETE /docs/sourcedb/:sourcedb/sourceid/:sourceid
def delete
raise SecurityError, "Not authorized" unless current_user && current_user.root? == true
divs = Doc.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "There is no such document." unless divs.present?
sourcedb = divs.first.sourcedb
divs.each{|div| div.destroy}
redirect_to doc_sourcedb_index_path(sourcedb)
end
# DELETE /docs/1
# DELETE /docs/1.json
def destroy
begin
doc = Doc.find(params[:id])
if params[:project_id].present?
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "There is no such project in your management." unless project.present?
project.docs.delete(doc)
expire_fragment("sourcedb_counts_#{project.name}")
expire_fragment("count_docs_#{project.name}")
expire_fragment("count_#{doc.sourcedb}_#{project.name}")
redirect_path = records_project_docs_path(params[:project_id])
else
raise SecurityError, "Not authorized" unless current_user && current_user.root? == true
doc.destroy
redirect_path = home_path
end
message = 'the document is deleted from the project.'
respond_to do |format|
format.html { redirect_to redirect_path }
format.json { render json: {message: message} }
format.txt { render text: message }
end
rescue => e
respond_to do |format|
format.html { redirect_to redirect_path, notice: e.message }
format.json { render json: {message: e.message}, status: :unprocessable_entity }
format.txt { render text: e.message, status: :unprocessable_entity }
end
end
end
def project_delete_doc
begin
project = Project.editable(current_user).find_by_name(params[:project_id])
raise "The project does not exist, or you are not authorized to make a change to the project.\n" unless project.present?
divs = project.docs.find_all_by_sourcedb_and_sourceid(params[:sourcedb], params[:sourceid])
raise "The document does not exist in the project.\n" unless divs.present?
divs.each{|div| project.delete_doc(div)}
expire_fragment("sourcedb_counts_#{project.name}")
expire_fragment("count_docs_#{project.name}")
expire_fragment("count_#{params[:sourcedb]}_#{project.name}")
message = "the document is deleted from the project.\n"
respond_to do |format|
format.html { redirect_to project_docs_path(project.name), notice:message }
format.json { render json: {message: message} }
format.txt { render text: message }
end
rescue => e
respond_to do |format|
format.html { redirect_to project_docs_path(project.name), notice:e.message }
format.json { render json: {message: e.message}, status: :unprocessable_entity }
format.txt { render text: e.message, status: :unprocessable_entity }
end
end
end
def store_span_rdf
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
projects = Project.for_index
docids = projects.inject([]){|col, p| (col + p.docs.pluck(:id))}.uniq
system = Project.find_by_name('system-maintenance')
delayed_job = Delayed::Job.enqueue StoreRdfizedSpansJob.new(system, docids, Pubann::Application.config.rdfizer_spans), queue: :general
Job.create({name:"Store RDFized spans for selected projects", project_id:system.id, delayed_job_id:delayed_job.id})
rescue => e
flash[:notice] = e.message
end
redirect_to project_path('system-maintenance')
end
def update_numbers
begin
raise RuntimeError, "Not authorized" unless current_user && current_user.root? == true
system = Project.find_by_name('system-maintenance')
delayed_job = Delayed::Job.enqueue UpdateAnnotationNumbersJob.new(nil), queue: :general
Job.create({name:"Update annotation numbers of each document", project_id:system.id, delayed_job_id:delayed_job.id})
result = {message: "The task, 'update annotation numbers of each document', created."}
redirect_to project_path('system-maintenance')
rescue => e
flash[:notice] = e.message
redirect_to home_path
end
end
# def autocomplete_sourcedb
# render :json => Doc.where(['LOWER(sourcedb) like ?', "%#{params[:term].downcase}%"]).collect{|doc| doc.sourcedb}.uniq
# end
end
|
# (c) 2008-2011 by Allgemeinbildung e.V., Bremen, Germany
# This file is part of Communtu.
# Communtu is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Communtu 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 Public License for more details.
# You should have received a copy of the GNU Affero Public License
# along with Communtu. If not, see <http://www.gnu.org/licenses/>.
class HomeController < ApplicationController
def title
if params[:action] == "impressum"
"Communtu: " + t(:imprint)
elsif params[:action] == "beteiligung"
"Communtu: " + t(:participation)
elsif params[:action] == "contact_us"
"Communtu: " + t(:view_home_contact_us_0)
elsif params[:action] == "news"
"Communtu: " + t(:news)
elsif params[:action] == "chat"
"Communtu: " + t(:chat)
elsif params[:action] == "about"
"Communtu: " + t(:about_us)
elsif params[:action] == "faq"
"Communtu: " + t(:view_home_faq_00)
elsif params[:action] == "donate"
"Communtu: " + t(:view_home_donate)
else
t(:view_layouts_application_21)
end
end
protect_from_forgery :only => [:create, :update, :destroy]
def home
@metapackges = Metapackage.find(:all,
:select => "base_packages.*, avg(ratings.rating) AS rating",
:joins => "LEFT JOIN ratings ON base_packages.id = ratings.rateable_id",
:conditions => "ratings.rateable_type = 'BasePackage'",
:group => "ratings.rateable_id HAVING COUNT(ratings.id) > 2",
:order => "rating DESC",
:limit => 5)
@info = Info.find(:first, :conditions => ['created_at > ?', Date.today-14], :order => 'created_at DESC' )
@livecds = Livecd.find(:all, :order => "downloaded DESC", :limit => 5, :conditions => "published = true")
end
def about
end
def derivatives
end
def auth_error
end
def icons
end
def mail
end
def news
if params[:announce] == "1" and I18n.locale.to_s == "de"
system "echo \"\" | mail -s \"announce\" -c info@toddy-franz.de -a \"FROM: #{current_user.email}\" communtu-announce-de+subscribe@googlegroups.com &"
flash[:notice] = t(:thanks_for_order)
elsif params[:announce] == "1"
system "echo \"\" | mail -s \"announce\" -c info@toddy-franz.de -a \"FROM: #{current_user.email}\" communtu-announce-en+subscribe@googlegroups.com &"
flash[:notice] = t(:thanks_for_order)
end
if params[:discuss] == "1" and I18n.locale.to_s == "de"
system "echo \"\" | mail -s \"discuss\" -c info@toddy-franz.de -a \"FROM: #{current_user.email}\" communtu-discuss-de+subscribe@googlegroups.com &"
flash[:notice] = t(:thanks_for_order)
elsif params[:discuss] == "1"
system "echo \"\" | mail -s \"discuss\" -c info@toddy-franz.de -a \"FROM: #{current_user.email}\" communtu-discuss-en+subscribe@googlegroups.com &"
flash[:notice] = t(:thanks_for_order)
end
@infos = Info.find(:all, :conditions => ['created_at > ?', Date.today-365], :order => 'created_at DESC' )
end
def donate
end
def email
@form_name = params[:form][:name]
@form_frage = params[:form][:frage]
u = if logged_in? then current_user else User.first end
MyMailer.deliver_mail(@form_name, @form_frage, u)
flash[:notice] = t(:controller_home_1)
redirect_to params[:form][:backlink]
end
def repo
@form_name = params[:form][:name]
@form_frage = params[:form][:frage]
MyMailer.deliver_repo(@form_name, @form_frage, current_user)
flash[:notice] = t(:controller_home_5)
redirect_to '/home'
end
def submit_mail
@form_email = params[:form][:email]
MyMailer.deliver_mailerror(@form_email)
flash[:notice] = t(:controller_home_2)
redirect_to '/home'
end
def faq
@faq = true
end
end
working on #1529
# (c) 2008-2011 by Allgemeinbildung e.V., Bremen, Germany
# This file is part of Communtu.
# Communtu is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# Communtu 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 Public License for more details.
# You should have received a copy of the GNU Affero Public License
# along with Communtu. If not, see <http://www.gnu.org/licenses/>.
class HomeController < ApplicationController
def title
if params[:action] == "impressum"
"Communtu: " + t(:imprint)
elsif params[:action] == "beteiligung"
"Communtu: " + t(:participation)
elsif params[:action] == "contact_us"
"Communtu: " + t(:view_home_contact_us_0)
elsif params[:action] == "news"
"Communtu: " + t(:news)
elsif params[:action] == "chat"
"Communtu: " + t(:chat)
elsif params[:action] == "about"
"Communtu: " + t(:about_us)
elsif params[:action] == "faq"
"Communtu: " + t(:view_home_faq_00)
elsif params[:action] == "donate"
"Communtu: " + t(:view_home_donate)
else
t(:view_layouts_application_21)
end
end
protect_from_forgery :only => [:create, :update, :destroy]
def home
@metapackges = Metapackage.find(:all,
:select => "base_packages.*, avg(ratings.rating) AS rating",
:joins => "LEFT JOIN ratings ON base_packages.id = ratings.rateable_id",
:conditions => "ratings.rateable_type = 'BasePackage'",
:group => "ratings.rateable_id HAVING COUNT(ratings.id) > 2",
:order => "rating DESC",
:limit => 5)
@info = Info.find(:first, :conditions => ['created_at > ?', Date.today-14], :order => 'created_at DESC' )
@livecds = Livecd.find(:all, :order => "downloaded DESC", :limit => 5, :conditions => {:published => true,:failed => false})
end
def about
end
def derivatives
end
def auth_error
end
def icons
end
def mail
end
def news
if params[:announce] == "1" and I18n.locale.to_s == "de"
system "echo \"\" | mail -s \"announce\" -c info@toddy-franz.de -a \"FROM: #{current_user.email}\" communtu-announce-de+subscribe@googlegroups.com &"
flash[:notice] = t(:thanks_for_order)
elsif params[:announce] == "1"
system "echo \"\" | mail -s \"announce\" -c info@toddy-franz.de -a \"FROM: #{current_user.email}\" communtu-announce-en+subscribe@googlegroups.com &"
flash[:notice] = t(:thanks_for_order)
end
if params[:discuss] == "1" and I18n.locale.to_s == "de"
system "echo \"\" | mail -s \"discuss\" -c info@toddy-franz.de -a \"FROM: #{current_user.email}\" communtu-discuss-de+subscribe@googlegroups.com &"
flash[:notice] = t(:thanks_for_order)
elsif params[:discuss] == "1"
system "echo \"\" | mail -s \"discuss\" -c info@toddy-franz.de -a \"FROM: #{current_user.email}\" communtu-discuss-en+subscribe@googlegroups.com &"
flash[:notice] = t(:thanks_for_order)
end
@infos = Info.find(:all, :conditions => ['created_at > ?', Date.today-365], :order => 'created_at DESC' )
end
def donate
end
def email
@form_name = params[:form][:name]
@form_frage = params[:form][:frage]
u = if logged_in? then current_user else User.first end
MyMailer.deliver_mail(@form_name, @form_frage, u)
flash[:notice] = t(:controller_home_1)
redirect_to params[:form][:backlink]
end
def repo
@form_name = params[:form][:name]
@form_frage = params[:form][:frage]
MyMailer.deliver_repo(@form_name, @form_frage, current_user)
flash[:notice] = t(:controller_home_5)
redirect_to '/home'
end
def submit_mail
@form_email = params[:form][:email]
MyMailer.deliver_mailerror(@form_email)
flash[:notice] = t(:controller_home_2)
redirect_to '/home'
end
def faq
@faq = true
end
end
|
class HomeController < ApplicationController
layout "home"
def index
@users = User.all
@sites = Site.all
end
end
featured sites must have images
class HomeController < ApplicationController
layout "home"
def index
@users = User.all
@featured_sites = Site.where("image_file_name > ''")
end
end
|
class HomeController < ApplicationController
def index
if user_signed_in?
@user_status = {
:status => 1,
:email => current_user.email,
:logouturl => destroy_user_session_path
}.to_json
else
@user_status = {
:status => 0,
:signupurl => new_user_registration_path,
:loginurl => new_user_session_path
}.to_json
end
end
end
Tidied up home controller - doesnt make unnecessary db calls anymore
class HomeController < ApplicationController
def index
# if user_signed_in?
# @user_status = {
# :status => 1,
# :email => current_user.email,
# :logouturl => destroy_user_session_path
# }.to_json
# else
# @user_status = {
# :status => 0,
# :signupurl => new_user_registration_path,
# :loginurl => new_user_session_path
# }.to_json
# end
end
end
|
class HomeController < Spree::BaseController
helper :products
respond_to :html
include Admin::BaseHelper
layout :choose_layout
def index
@searcher = Spree::Config.searcher_class.new(params)
domain = get_sub_domain(current_subdomain)
@products = @searcher.retrieve_products(domain)
respond_with(@products)
end
def choose_layout
if (request.url.include?(APP_CONFIG['domain_url']) || request.url.include?(APP_CONFIG['secure_domain_url']))
return "saas"
else
return "spree_application"
end
end
end
added paginate require
class HomeController < Spree::BaseController
require 'will_paginate/array'
helper :products
respond_to :html
include Admin::BaseHelper
layout :choose_layout
def index
@searcher = Spree::Config.searcher_class.new(params)
domain = get_sub_domain(current_subdomain)
@products = @searcher.retrieve_products(domain)
respond_with(@products)
end
def choose_layout
if (request.url.include?(APP_CONFIG['domain_url']) || request.url.include?(APP_CONFIG['secure_domain_url']))
return "saas"
else
return "spree_application"
end
end
end |
# encoding: UTF-8
class HomeController < ApplicationController
hdo_caches_page :index, :contact, :join, :support, :people,
:about_method, :member, :future, :robots
def index
@issues = Issue.published.random(6)
@parties = Party.order(:name)
end
def about
if params[:lang] == "en"
render :about, :locale => "en"
end
end
def robots
if Rails.env.production?
robots = ''
else
robots = "User-Agent: *\nDisallow: /\n"
end
render text: robots, layout: false, content_type: "text/plain"
end
# don't override Object#method
def about_method
end
def contact
end
def join
end
def support
end
def member
end
def future
end
def revision
rev = AppConfig['revision'] ||= (
file = Rails.root.join('REVISION')
file.exist? ? file.read : `git rev-parse HEAD`.strip
)
render :text => rev, content_type: 'text/plain'
end
def healthz
head :ok
end
def people
users = User.where(active: true)
@board, @contributors = users.partition { |e| e.board? }
@alumni = [
Person.new('Tage Augustson'),
Person.new('Martin Bekkelund'),
Person.new('Anders Berg Hansen'),
Person.new('Cathrine Berg-Nielsen'),
Person.new('Kristian Bysheim'),
Person.new('Anne Raaum Christensen'),
Person.new('Madeleine Skjelland Eriksen'),
Person.new('Linn Katrine Erstad'),
Person.new('Marte Haabeth Grindaker'),
Person.new('Vilde Grønn'),
Person.new('Rigmor Haga'),
Person.new('Svein Halvor Halvorsen'),
Person.new('Kristiane Hammer'),
Person.new('Vegar Heir'),
Person.new('Dina Hestad'),
Person.new('Thomas Huang'),
Person.new('Elida Høeg'),
Person.new('Tor Håkon Inderberg'),
Person.new('Esben Jensen'),
Person.new('Nina Jensen'),
Person.new('Daniel Kafkas'),
Person.new('Einar Kjerschow'),
Person.new('Øystein Jerkø Kostøl'),
Person.new('Ingrid Lomelde'),
Person.new('Ellen M. E. Lundring'),
Person.new('Liv Arntzen Løchen'),
Person.new('Magnus Løseth'),
Person.new('Carl Martin Rosenberg'),
Person.new('Marit Sjøvaag Marino'),
Person.new('Joanna Merker'),
Person.new('Sara Mjelva'),
Person.new('Silje Nyløkken'),
Person.new('Endre Ottosen'),
Person.new('Erik Seierstad'),
Person.new('Osman Siddique'),
Person.new('Tommy Steinsli'),
Person.new('Cosimo Streppone'),
Person.new('Einar Sundin'),
Person.new('Eirik Swensen'),
Person.new('Ole Martin Volle'),
Person.new('Guro Øistensen')
]
end
class Person
attr_reader :name, :image, :email, :bio
def initialize(name, email = nil, image = nil, bio = nil)
@name, @email, @image, @bio = name, email, image, bio
end
end
end
Order user list by name
# encoding: UTF-8
class HomeController < ApplicationController
hdo_caches_page :index, :contact, :join, :support, :people,
:about_method, :member, :future, :robots
def index
@issues = Issue.published.random(6)
@parties = Party.order(:name)
end
def about
if params[:lang] == "en"
render :about, :locale => "en"
end
end
def robots
if Rails.env.production?
robots = ''
else
robots = "User-Agent: *\nDisallow: /\n"
end
render text: robots, layout: false, content_type: "text/plain"
end
# don't override Object#method
def about_method
end
def contact
end
def join
end
def support
end
def member
end
def future
end
def revision
rev = AppConfig['revision'] ||= (
file = Rails.root.join('REVISION')
file.exist? ? file.read : `git rev-parse HEAD`.strip
)
render :text => rev, content_type: 'text/plain'
end
def healthz
head :ok
end
def people
@board, @contributors = User.where(active: true).order(:name).partition { |e| e.board? }
@alumni = [
Person.new('Tage Augustson'),
Person.new('Martin Bekkelund'),
Person.new('Anders Berg Hansen'),
Person.new('Cathrine Berg-Nielsen'),
Person.new('Kristian Bysheim'),
Person.new('Anne Raaum Christensen'),
Person.new('Madeleine Skjelland Eriksen'),
Person.new('Linn Katrine Erstad'),
Person.new('Marte Haabeth Grindaker'),
Person.new('Vilde Grønn'),
Person.new('Rigmor Haga'),
Person.new('Svein Halvor Halvorsen'),
Person.new('Kristiane Hammer'),
Person.new('Vegar Heir'),
Person.new('Dina Hestad'),
Person.new('Thomas Huang'),
Person.new('Elida Høeg'),
Person.new('Tor Håkon Inderberg'),
Person.new('Esben Jensen'),
Person.new('Nina Jensen'),
Person.new('Daniel Kafkas'),
Person.new('Einar Kjerschow'),
Person.new('Øystein Jerkø Kostøl'),
Person.new('Ingrid Lomelde'),
Person.new('Ellen M. E. Lundring'),
Person.new('Liv Arntzen Løchen'),
Person.new('Magnus Løseth'),
Person.new('Carl Martin Rosenberg'),
Person.new('Marit Sjøvaag Marino'),
Person.new('Joanna Merker'),
Person.new('Sara Mjelva'),
Person.new('Silje Nyløkken'),
Person.new('Endre Ottosen'),
Person.new('Erik Seierstad'),
Person.new('Osman Siddique'),
Person.new('Tommy Steinsli'),
Person.new('Cosimo Streppone'),
Person.new('Einar Sundin'),
Person.new('Eirik Swensen'),
Person.new('Ole Martin Volle'),
Person.new('Guro Øistensen')
]
end
class Person
attr_reader :name, :image, :email, :bio
def initialize(name, email = nil, image = nil, bio = nil)
@name, @email, @image, @bio = name, email, image, bio
end
end
end
|
require_relative '../../lib/phonetic_alphabet'
require_relative '../../lib/string_cleaner'
require_relative '../../lib/time_now'
require_relative '../lib/hidden_file_remover'
class KataController < ApplicationController
def individual
@kata_id = kata.id
@avatar_name = avatar.name
@phonetic = Phonetic.spelling(kata.id[0..5])
end
def group
@kata_id = kata.id
@phonetic = Phonetic.spelling(kata.id[0..5])
end
def edit
@kata = kata
@avatar = avatar
@visible_files = @avatar.visible_files
@traffic_lights = @avatar.lights
@output = @visible_files['output']
@title = 'test:' + @kata.id[0..5] + ':' + @avatar.name
end
def run_tests
case runner_choice
when 'stateless'
runner.set_hostname_port_stateless
when 'stateful'
runner.set_hostname_port_stateful
#when 'processful'
#runner.set_hostname_port_processful
end
incoming = params[:file_hashes_incoming]
outgoing = params[:file_hashes_outgoing]
delta = FileDeltaMaker.make_delta(incoming, outgoing)
files = received_files
@avatar = Avatar.new(self, kata, avatar_name)
args = []
args << delta
args << files
args << max_seconds # eg 10
args << image_name # eg 'cyberdojofoundation/gcc_assert'
stdout,stderr,status,@colour,
@new_files,@deleted_files,@changed_files = avatar.test(*args)
if @colour == 'timed_out'
stdout = timed_out_message(max_seconds) + stdout
end
# If there is a file called output remove it otherwise
# it will interfere with the @output pseudo-file.
@new_files.delete('output')
# don't show generated hidden filenames
remove_hidden_files(@new_files, hidden_filenames)
# Storer's snapshot exactly mirrors the files after the test-event
# has completed. That is, after a test-event completes if you
# refresh the page in the browser then nothing will change.
@deleted_files.keys.each do |filename|
files.delete(filename)
end
@new_files.each do |filename,content|
files[filename] = content
end
@changed_files.each do |filename,content|
files[filename] = content
end
# avatar.tested() saves the test results to storer which
# also validates a kata with the given id exists.
# It could become a fire-and-forget method.
# This might decrease run_tests() response time.
# Also, I have tried to make it fire-and-forget using the
# spawnling gem and it breaks a test in a non-obvious way.
avatar.tested(files, time_now, stdout, stderr, @colour)
@output = stdout + stderr
respond_to do |format|
format.js { render layout: false }
format.json { show_json }
end
end
# - - - - - - - - - - - - - - - - - -
def show_json
# https://atom.io/packages/cyber-dojo
render :json => {
'visible_files' => avatar.visible_files,
'avatar' => avatar.name,
'csrf_token' => form_authenticity_token,
'lights' => avatar.lights.map { |light| light.to_json }
}
end
private # = = = = = = = = = = = = = =
include HiddenFileRemover
include StringCleaner
include TimeNow
def received_files
seen = {}
(params[:file_content] || {}).each do |filename, content|
content = cleaned(content)
# Important to ignore output as it's not a 'real' file
unless filename == 'output'
# Cater for windows line endings from windows browser
seen[filename] = content.gsub(/\r\n/, "\n")
end
end
seen
end
# - - - - - - - - - - - - - - - - - -
def timed_out_message(max_seconds)
[
"Unable to complete the tests in #{max_seconds} seconds.",
'Is there an accidental infinite loop?',
'Is the server very busy?',
'Please try again.'
].join("\n") + "\n"
end
end
refactoring; simplify controller method code
require_relative '../../lib/phonetic_alphabet'
require_relative '../../lib/string_cleaner'
require_relative '../../lib/time_now'
require_relative '../lib/hidden_file_remover'
class KataController < ApplicationController
def individual
@kata_id = kata.id
@avatar_name = avatar.name
@phonetic = Phonetic.spelling(kata.id[0..5])
end
def group
@kata_id = kata.id
@phonetic = Phonetic.spelling(kata.id[0..5])
end
def edit
@kata = kata
@avatar = avatar
@visible_files = @avatar.visible_files
@traffic_lights = @avatar.lights
@output = @visible_files['output']
@title = 'test:' + @kata.id[0..5] + ':' + @avatar.name
end
def run_tests
case runner_choice
when 'stateless'
runner.set_hostname_port_stateless
when 'stateful'
runner.set_hostname_port_stateful
#when 'processful'
#runner.set_hostname_port_processful
end
incoming = params[:file_hashes_incoming]
outgoing = params[:file_hashes_outgoing]
delta = FileDeltaMaker.make_delta(incoming, outgoing)
files = received_files
@avatar = Avatar.new(self, kata, avatar_name)
args = []
args << delta
args << files
args << max_seconds # eg 10
args << image_name # eg 'cyberdojofoundation/gcc_assert'
stdout,stderr,status,@colour,
@new_files,@deleted_files,@changed_files = avatar.test(*args)
if @colour == 'timed_out'
stdout = timed_out_message(max_seconds) + stdout
end
# If there is a file called output remove it otherwise
# it will interfere with the @output pseudo-file.
@new_files.delete('output')
# don't show generated hidden filenames
remove_hidden_files(@new_files, hidden_filenames)
# Storer's snapshot exactly mirrors the files after the test-event
# has completed. That is, after a test-event completes if you
# refresh the page in the browser then nothing will change.
@deleted_files.keys.each do |filename|
files.delete(filename)
end
@new_files.each do |filename,content|
files[filename] = content
end
@changed_files.each do |filename,content|
files[filename] = content
end
# avatar.tested() saves the test results to storer which
# also validates a kata with the given id exists.
# It could become a fire-and-forget method.
# This might decrease run_tests() response time.
# Also, I have tried to make it fire-and-forget using the
# spawnling gem and it breaks a test in a non-obvious way.
avatar.tested(files, time_now, stdout, stderr, @colour)
@output = stdout + stderr
respond_to do |format|
format.js { render layout: false }
format.json { show_json }
end
end
# - - - - - - - - - - - - - - - - - -
def show_json
# https://atom.io/packages/cyber-dojo
render :json => {
'visible_files' => avatar.visible_files,
'avatar' => avatar.name,
'csrf_token' => form_authenticity_token,
'lights' => avatar.lights.map { |light| light.to_json }
}
end
private # = = = = = = = = = = = = = =
include HiddenFileRemover
include StringCleaner
include TimeNow
def received_files
seen = {}
(params[:file_content] || {}).each do |filename, content|
# Important to ignore output as it's not a 'real' file
unless filename == 'output'
content = cleaned(content)
# Cater for windows line endings from windows browser
seen[filename] = content.gsub(/\r\n/, "\n")
end
end
seen
end
# - - - - - - - - - - - - - - - - - -
def timed_out_message(max_seconds)
[
"Unable to complete the tests in #{max_seconds} seconds.",
'Is there an accidental infinite loop?',
'Is the server very busy?',
'Please try again.'
].join("\n") + "\n"
end
end
|
class MainController < ApplicationController
def index
end
def poligraft
if (@result = Result.create!(:source_url => params[:url], :source_text => params[:text]))
@result.process_entities
if params[:json] == "1"
redirect_to "/" + @result.slug + ".json"
else
redirect_to "/" + @result.slug
end
else
flash[:error] = "Sorry, couldn't process that input."
redirect_to :root
end
end
def result
@result = Result.first(:slug => params[:slug])
response_code = @result.processed ? 200 : 202
if @result
respond_to do |format|
format.html
format.json { render :json => @result.to_json(:methods => [:source_content],
:except => [:source_text]),
:status => response_code }
end
else
render :file => "#{RAILS_ROOT}/public/404.html", :layout => false, :status => 404
end
end
def feedback
if params[:feedback]
@feedback = Feedback.create(params[:feedback])
if @feedback.save
Notifier.feedback_email(@feedback).deliver
redirect_to thanks_path
else
flash[:error] = "Error saving. Please fill in all fields."
end
else
@feedback = Feedback.new
end
end
def about
end
def plucked
urls = ['http://www.nytimes.com/2010/05/06/opinion/06gcollins.html',
'http://www.politico.com/news/stories/0610/38121.html',
'http://www.theatlantic.com/politics/archive/2010/07/wikileak-ethics/60660/',
'http://indexjournal.com/articles/2010/07/30/news/b073010%20edwards.txt',
'http://www.cbsnews.com/stories/2010/07/15/politics/main6681481.shtml',
'http://www.latimes.com/business/la-fi-financial-reform-20100716,0,2303004.story',
'http://www.washingtonpost.com/wp-dyn/content/article/2010/07/30/AR2010073000806.html']
@articles = urls.map { |url| ContentPlucker.pluck_from url }
end
end
Set response_code in the right place [#4544678]
class MainController < ApplicationController
def index
end
def poligraft
if (@result = Result.create!(:source_url => params[:url], :source_text => params[:text]))
@result.process_entities
if params[:json] == "1"
redirect_to "/" + @result.slug + ".json"
else
redirect_to "/" + @result.slug
end
else
flash[:error] = "Sorry, couldn't process that input."
redirect_to :root
end
end
def result
@result = Result.first(:slug => params[:slug])
if @result
response_code = @result.processed ? 200 : 202
respond_to do |format|
format.html
format.json { render :json => @result.to_json(:methods => [:source_content],
:except => [:source_text]),
:status => response_code }
end
else
render :file => "#{RAILS_ROOT}/public/404.html", :layout => false, :status => 404
end
end
def feedback
if params[:feedback]
@feedback = Feedback.create(params[:feedback])
if @feedback.save
Notifier.feedback_email(@feedback).deliver
redirect_to thanks_path
else
flash[:error] = "Error saving. Please fill in all fields."
end
else
@feedback = Feedback.new
end
end
def about
end
def plucked
urls = ['http://www.nytimes.com/2010/05/06/opinion/06gcollins.html',
'http://www.politico.com/news/stories/0610/38121.html',
'http://www.theatlantic.com/politics/archive/2010/07/wikileak-ethics/60660/',
'http://indexjournal.com/articles/2010/07/30/news/b073010%20edwards.txt',
'http://www.cbsnews.com/stories/2010/07/15/politics/main6681481.shtml',
'http://www.latimes.com/business/la-fi-financial-reform-20100716,0,2303004.story',
'http://www.washingtonpost.com/wp-dyn/content/article/2010/07/30/AR2010073000806.html']
@articles = urls.map { |url| ContentPlucker.pluck_from url }
end
end |
class MainController < ApplicationController
def home
@surveys = Survey.available_to_complete
respond_to do |format|
format.html { render '/home/index' }
end
end
def comment
@topic = params[:topic]
@title = params[:title] || @topic
@back = params[:back]
# Look for a question with this topic and use the help text
@topic_help = begin
Question.find(params[:question_id]).help_text
rescue ActiveRecord::RecordNotFound
''
end
end
def discussion
@topic = 'general'
@topic_help = I18n.t 'general', scope: :discussions, default: ''
render 'comment'
end
def status
@job_count = Delayed::Job.count
@counts = {
'certificates' => Certificate.counts,
'datasets' => ResponseSet.counts
}
@head_commit = `git rev-parse HEAD`
render '/home/status'
end
def status_csv
csv = Rackspace.fetch_cache("statistics.csv")
render text: csv, content_type: "text/csv"
end
def status_response_sets
@response_sets = ResponseSet.all.map do |m|
{
id: m.id,
created_at: m.created_at.to_i,
state: m.aasm_state
}
end
respond_to do |format|
format.json { render json: @response_sets.to_json }
end
end
def status_events
@events = DevEvent.order('created_at DESC').page(params[:page]).per(100)
end
# A user pings this url if they have js enabled, so we can tell surveyor
# not to find unnecessary requirements.
def has_js
session[:surveyor_javascript] = "enabled"
render :text => 'ok'
end
# method for clearing the cache
def clear_cache
Rails.cache.clear
render :text => 'cleared'
end
# mostly lifted from surveyor#create
def start_questionnaire
# bypassing the need for the user to select the survey - since we're launching with just one 'legislation'
# When multiple legislations are available, this value will need to be provided by the form
access_code = params[:survey_access_code] ||
current_user.try(:default_jurisdiction) ||
Survey::DEFAULT_ACCESS_CODE
# if a dataset isn't supplied, create one for an authenticated user, or mock one for unauthenticated
@dataset = Dataset.find_by_id(params[:dataset_id]) || (user_signed_in? ? current_user.datasets.create : Dataset.create)
authorize! :update, @dataset
# use the most recent survey
@survey = Survey.where(:access_code => access_code).order("survey_version DESC").first
@response_set = ResponseSet.
create(:survey => @survey,
:user_id => current_user.try(:id),
:dataset_id => @dataset.id
)
if @survey && @response_set
session[:response_set_id] = current_user ? nil : @response_set.id
if params[:source_response_set_id]
source_response_set = ResponseSet.find(params[:source_response_set_id]) # TODO: ensure user has rights to copy the response set answers?
@response_set.copy_answers_from_response_set!(source_response_set)
end
# flash[:notice] = t('surveyor.survey_started_success')
redirect_to(surveyor.edit_my_survey_path(
:survey_code => @survey.access_code, :response_set_code => @response_set.access_code))
else
flash[:notice] = t('surveyor.unable_to_find_that_legislation')
redirect_to (user_signed_in? ? dashboard_path : root_path)
end
end
end
Get head commit from Rails root rather than git
class MainController < ApplicationController
def home
@surveys = Survey.available_to_complete
respond_to do |format|
format.html { render '/home/index' }
end
end
def comment
@topic = params[:topic]
@title = params[:title] || @topic
@back = params[:back]
# Look for a question with this topic and use the help text
@topic_help = begin
Question.find(params[:question_id]).help_text
rescue ActiveRecord::RecordNotFound
''
end
end
def discussion
@topic = 'general'
@topic_help = I18n.t 'general', scope: :discussions, default: ''
render 'comment'
end
def status
@job_count = Delayed::Job.count
@counts = {
'certificates' => Certificate.counts,
'datasets' => ResponseSet.counts
}
@head_commit = Rails.root.to_s.split("/").last
render '/home/status'
end
def status_csv
csv = Rackspace.fetch_cache("statistics.csv")
render text: csv, content_type: "text/csv"
end
def status_response_sets
@response_sets = ResponseSet.all.map do |m|
{
id: m.id,
created_at: m.created_at.to_i,
state: m.aasm_state
}
end
respond_to do |format|
format.json { render json: @response_sets.to_json }
end
end
def status_events
@events = DevEvent.order('created_at DESC').page(params[:page]).per(100)
end
# A user pings this url if they have js enabled, so we can tell surveyor
# not to find unnecessary requirements.
def has_js
session[:surveyor_javascript] = "enabled"
render :text => 'ok'
end
# method for clearing the cache
def clear_cache
Rails.cache.clear
render :text => 'cleared'
end
# mostly lifted from surveyor#create
def start_questionnaire
# bypassing the need for the user to select the survey - since we're launching with just one 'legislation'
# When multiple legislations are available, this value will need to be provided by the form
access_code = params[:survey_access_code] ||
current_user.try(:default_jurisdiction) ||
Survey::DEFAULT_ACCESS_CODE
# if a dataset isn't supplied, create one for an authenticated user, or mock one for unauthenticated
@dataset = Dataset.find_by_id(params[:dataset_id]) || (user_signed_in? ? current_user.datasets.create : Dataset.create)
authorize! :update, @dataset
# use the most recent survey
@survey = Survey.where(:access_code => access_code).order("survey_version DESC").first
@response_set = ResponseSet.
create(:survey => @survey,
:user_id => current_user.try(:id),
:dataset_id => @dataset.id
)
if @survey && @response_set
session[:response_set_id] = current_user ? nil : @response_set.id
if params[:source_response_set_id]
source_response_set = ResponseSet.find(params[:source_response_set_id]) # TODO: ensure user has rights to copy the response set answers?
@response_set.copy_answers_from_response_set!(source_response_set)
end
# flash[:notice] = t('surveyor.survey_started_success')
redirect_to(surveyor.edit_my_survey_path(
:survey_code => @survey.access_code, :response_set_code => @response_set.access_code))
else
flash[:notice] = t('surveyor.unable_to_find_that_legislation')
redirect_to (user_signed_in? ? dashboard_path : root_path)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.