Skip to content

Commit

Permalink
Merge pull request #103 from mezuro/likeno
Browse files Browse the repository at this point in the history
Integrate Likeno

Lots of code regarding HTTP requests and resource management has been
extracted into a separated gem.
  • Loading branch information
rafamanzo committed Mar 30, 2016
2 parents b7ea668 + e0aacac commit a2bcaba
Show file tree
Hide file tree
Showing 49 changed files with 136 additions and 1,707 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
@is_error = false
begin
KalibroClient::Entities::Processor::MetricCollectorDetails.find_by_name!("Avalio")
rescue KalibroClient::Errors::RecordNotFound
rescue Likeno::Errors::RecordNotFound
@is_error = true
end
end
Expand Down
4 changes: 2 additions & 2 deletions features/step_definitions/metric_configuration_steps.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
inexistent_id = rand(Time.now.to_i)
begin
KalibroClient::Entities::Configurations::MetricConfiguration.find(inexistent_id)
rescue KalibroClient::Errors::RecordNotFound
rescue Likeno::Errors::RecordNotFound
@is_error = true
end
end
Expand Down Expand Up @@ -81,7 +81,7 @@
end

Then(/^the metric configuration should no longer exist$/) do
expect { KalibroClient::Entities::Configurations::MetricConfiguration.find(@metric_configuration.id)}.to raise_error(KalibroClient::Errors::RecordNotFound)
expect { KalibroClient::Entities::Configurations::MetricConfiguration.find(@metric_configuration.id)}.to raise_error(Likeno::Errors::RecordNotFound)
end

Then(/^the metric configuration should exist$/) do
Expand Down
2 changes: 1 addition & 1 deletion features/step_definitions/module_result_steps.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
@is_error = false
begin
KalibroClient::Entities::Processor::ModuleResult.find(-1)
rescue KalibroClient::Errors::RecordNotFound
rescue Likeno::Errors::RecordNotFound
@is_error = true
end
end
Expand Down
3 changes: 0 additions & 3 deletions features/support/env.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@
# Kalibro hooks
require 'kalibro_client/kalibro_cucumber_helpers/hooks'

# Configuring the right hooks
KalibroClient::KalibroCucumberHelpers.configure_from_yml("#{__dir__}/kalibro_cucumber_helpers.yml")

# The gem itself
require 'kalibro_client'

Expand Down
1 change: 1 addition & 0 deletions kalibro_client.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,5 @@ Gem::Specification.new do |spec|

spec.add_dependency "activesupport", ">= 2.2.1" #version in which underscore was introduced
spec.add_dependency "faraday_middleware", "~> 0.9"
spec.add_dependency "likeno", "~> 1.1"
end
43 changes: 4 additions & 39 deletions lib/kalibro_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,49 +14,14 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

require 'yaml'
require 'logger'
require 'likeno'
require "kalibro_client/version"
require "kalibro_client/errors"
require "kalibro_client/entities"

module KalibroClient
@config = {
processor_address: "http://localhost:8082",
configurations_address: "http://localhost:8083"
}
# Apply default configuration to Likeno
Likeno.configure(processor_address: "http://localhost:8082",
configurations_address: "http://localhost:8083")

@valid_config_keys = @config.keys

@logger = Logger.new(STDOUT)

# Configure through hash
def KalibroClient.configure(opts = {})
opts.each {|k,v| @config[k.to_sym] = v if @valid_config_keys.include? k.to_sym}
end

# Configure through yaml file
def KalibroClient.configure_with(path_to_yaml_file)
begin
config = YAML::load(IO.read(path_to_yaml_file))
rescue Errno::ENOENT
logger.warn("YAML configuration file couldn't be found. Using defaults."); return
rescue Psych::SyntaxError
logger.warn("YAML configuration file contains invalid syntax. Using defaults."); return
end

configure(config)
end

def KalibroClient.config
@config
end

def KalibroClient.logger
@logger
end

def KalibroClient.logger=(logger)
@logger = logger
end
end
217 changes: 11 additions & 206 deletions lib/kalibro_client/entities/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,218 +14,23 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

require 'faraday_middleware'
require 'kalibro_client/helpers/hash_converters'
require 'kalibro_client/helpers/request_methods'
require 'likeno'
require 'kalibro_client/errors'

module KalibroClient
module Entities
class Base
attr_accessor :kalibro_errors, :persisted

def initialize(attributes={}, persisted=false)
attributes.each { |field, value| send("#{field}=", value) if self.class.is_valid?(field) }
@kalibro_errors = []
@persisted = persisted
end

def to_hash(options={})
hash = Hash.new
excepts = options[:except].nil? ? [] : options[:except]
excepts << "kalibro_errors"
excepts << "persisted"
fields.each do |field|
hash = field_to_hash(field).merge(hash) if !excepts.include?(field)
end
hash
end

def self.request(action, params = {}, method = :post, prefix="")
response = client.send(method) do |request|
url = "/#{endpoint}/#{action}".gsub(":id", params[:id].to_s)
url = "/#{prefix}#{url}" unless prefix.empty?
request.url url
request.body = params unless method == :get || params.empty?
request.options.timeout = 300
request.options.open_timeout = 300
end

if response.success?
response.body
# FIXME This condition was added to preserve the deprecated error codes that are returned by kalibro processor
elsif response.status == 404 || (response.body.key?('errors') && /NotFound/ === response.body['errors'])
raise KalibroClient::Errors::RecordNotFound.new(response: response)
else
raise KalibroClient::Errors::RequestError.new(response: response)
end
end


def self.to_object value
value.kind_of?(Hash) ? new(value, true) : value
end

def self.to_objects_array value
array = value.kind_of?(Array) ? value : [value]
array.each.map { |element| to_object(element) }
end

def save
if persisted?
self.update
else
without_request_error? do
response = self.class.request(save_action, save_params, :post, save_prefix)

self.id = response[instance_class_name]["id"]
self.created_at = response[instance_class_name]["created_at"] unless response[instance_class_name]["created_at"].nil?
self.updated_at = response[instance_class_name]["updated_at"] unless response[instance_class_name]["updated_at"].nil?
@persisted = true
end
end
end

def save!
return true if save
raise KalibroClient::Errors::RecordInvalid.new(self)
class Base < Likeno::Entity
# We do not track coverage here as it is deprecated and will be removed soon
# :nocov:
def kalibro_errors
STDERR.puts "DEPRECATED: use 'likeno_errors' instead of 'kalibro_errors'."
self.likeno_errors
end
# :nocov:

def self.create(attributes={})
new_model = new attributes
new_model.save
new_model
def self.module_name
'KalibroClient'
end

def update(attributes={})
attributes.each { |field, value| send("#{field}=", value) if self.class.is_valid?(field) }
without_request_error? do
self.class.request(update_action, update_params, :put, update_prefix)
end
end

def ==(another)
unless self.class == another.class
return false
end

self.variable_names.each do |name|
next if name == "created_at" or name == "updated_at" or name == "persisted"
unless self.send("#{name}") == another.send("#{name}") then
return false
end
end

return true
end

def self.exists?(id)
request(exists_action, id_params(id), :get)['exists']
end

def self.find(id)
response = request(find_action, id_params(id), :get)
new(response[entity_name], true)
end

def destroy
without_request_error? do
response = self.class.request(destroy_action, destroy_params, :delete, destroy_prefix)
@persisted = false
end
end

def self.create_objects_array_from_hash (response)
create_array_from_hash(response[entity_name.pluralize]).map { |hash| new(hash, true) }
end

def self.create_array_from_hash (response)
response = [] if response.nil?
response = [response] if response.is_a?(Hash)
response
end

alias_method :persisted?, :persisted

protected

def instance_variable_names
instance_variables.map { |var| var.to_s }
end

def fields
instance_variable_names.each.collect { |variable| variable.to_s.sub(/@/, '') }
end

def variable_names
instance_variable_names.each.collect { |variable| variable.to_s.sub(/@/, '') }
end

def self.address
raise NotImplementedError
end

# TODO: probably the connection could be a class static variable.
def self.client
Faraday.new(:url => KalibroClient.config[address]) do |conn|
conn.request :json
conn.response :json, :content_type => /\bjson$/
conn.adapter Faraday.default_adapter # make requests with Net::HTTP
end
end

def self.is_valid?(field)
field.to_s[0] != '@' and field != :attributes! and (field =~ /attributes!/).nil? and (field.to_s =~ /xsi/).nil? and (field.to_s =~ /errors/).nil?
end

# TODO rename to instance_entity_name
def instance_class_name
self.class.entity_name
end

include RequestMethods
extend RequestMethods::ClassMethods

def add_error(exception)
@kalibro_errors << exception
end

def self.endpoint
entity_name.pluralize
end

def self.entity_name
# This loop is a generic way to make this work even when the children class has a different name
entity_class = self
until entity_class.name.include?("KalibroClient::Entities::") do
entity_class = entity_class.superclass
end

return entity_class.name.split("::").last.underscore.downcase
end

def without_request_error?(&block)
begin
block.call
true
rescue KalibroClient::Errors::RecordNotFound => error
raise error
rescue KalibroClient::Errors::RequestError => error
raise error if error.response.status.between?(500, 599)

response_errors = error.response.body['errors']
if response_errors.is_a?(Array)
response_errors.each { |error_msg| add_error(error_msg) }
elsif !response_errors.nil?
add_error response_errors
else
add_error error
end

false
end
end

include HashConverters
end
end
end
6 changes: 3 additions & 3 deletions lib/kalibro_client/entities/configurations/base.rb
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
require 'kalibro_client/helpers/date_attributes'
require 'likeno/helpers/date_attributes'

module KalibroClient
module Entities
module Configurations
class Base < KalibroClient::Entities::Base
include DateAttributes
include Likeno::DateAttributes

def self.address
:configurations_address
Likeno.config[:configurations_address]
end
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,6 @@ def id=(value)
@id = value.to_i
end

def self.all
create_objects_array_from_hash(request('', {}, :get))
end

def metric_configurations
KalibroClient::Entities::Configurations::MetricConfiguration.create_objects_array_from_hash(self.class.request(':id/metric_configurations', {id: id}, :get))
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def weight=(value)
end

def update_attributes(attributes={})
attributes.each { |field, value| send("#{field}=", value) if self.class.is_valid?(field) }
attributes.each { |field, value| send("#{field}=", value) if self.class.valid?(field) }
save
end

Expand All @@ -68,24 +68,6 @@ def self.metric_configurations_of(configuration_id)
create_objects_array_from_hash(request('', {}, :get, "kalibro_configurations/#{configuration_id}"))
end

def self.find(id)
begin
metric_configuration = request(':id', {id: id}, :get)
return new(metric_configuration['metric_configuration'], true)
#FIXME Temporary until KalibroProcessor returns proper http statuses
rescue KalibroClient::Errors::RequestError
raise KalibroClient::Errors::RecordNotFound
end
end

def self.exists?(id)
begin
return true unless find(id).nil?
rescue KalibroClient::Errors::RecordNotFound
return false
end
end

def kalibro_ranges
KalibroClient::Entities::Configurations::KalibroRange.create_objects_array_from_hash(self.class.request(':id/kalibro_ranges', {id: id}, :get))
end
Expand Down
Loading

0 comments on commit a2bcaba

Please sign in to comment.