From e6eb389d41e30925341a95b8b8cfcc9b75195e66 Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 25 Mar 2016 17:52:52 -0400 Subject: [PATCH 01/42] Removed targetScheme from name-translation example. --- examples/name-translation.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/name-translation.rb b/examples/name-translation.rb index 2a640bb..214c0d4 100644 --- a/examples/name-translation.rb +++ b/examples/name-translation.rb @@ -26,8 +26,7 @@ content = { name: translated_name_data, targetLanguage: "eng", - targetScript: "Latn", - targetScheme: "IC" + targetScript: "Latn" } JSONbody = content.to_json From dc63958a9c826c4eba554113fc7bc340bc5ac108 Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 15 Apr 2016 10:24:14 -0400 Subject: [PATCH 02/42] First version of Ruby binding --- examples/categories.rb | 36 +- examples/docker/Dockerfile | 11 +- examples/docker/run_ruby.sh | 19 +- examples/entities.rb | 37 +- examples/entities_linked.rb | 37 +- examples/info.rb | 26 +- examples/language.rb | 36 +- examples/morphology_complete.rb | 36 +- examples/morphology_compound-components.rb | 35 -- examples/morphology_compound_components.rb | 15 + examples/morphology_han-readings.rb | 35 -- examples/morphology_han_readings.rb | 15 + examples/morphology_lemmas.rb | 36 +- examples/morphology_parts-of-speech.rb | 35 -- examples/morphology_parts_of_speech.rb | 15 + examples/name_similarity.rb | 39 +- examples/name_translation.rb | 40 +- examples/ping.rb | 26 +- examples/relationships.rb | 36 +- examples/sentences.rb | 39 +- examples/sentiment.rb | 62 +-- examples/tokens.rb | 36 +- mock-data/request/categories.json | 1 + mock-data/request/entities.json | 1 + mock-data/request/entities_linked.json | 1 + mock-data/request/language.json | 1 + mock-data/request/morphology_complete.json | 1 + .../morphology_compound_components.json | 1 + .../request/morphology_han_readings.json | 1 + mock-data/request/morphology_lemmas.json | 1 + .../request/morphology_parts_of_speech.json | 1 + mock-data/request/name_similarity.json | 1 + mock-data/request/name_translation.json | 1 + mock-data/request/relationships.json | 1 + mock-data/request/sentences.json | 1 + mock-data/request/sentiment.json | 1 + mock-data/request/tokens.json | 1 + parameters.rb | 68 +++ request_builder.rb | 112 ++++ rosette_api.rb | 122 +++++ rosette_api_error.rb | 8 + tests/tests.rb | 486 ++++++++++++++++++ 42 files changed, 992 insertions(+), 521 deletions(-) delete mode 100644 examples/morphology_compound-components.rb create mode 100644 examples/morphology_compound_components.rb delete mode 100644 examples/morphology_han-readings.rb create mode 100644 examples/morphology_han_readings.rb delete mode 100644 examples/morphology_parts-of-speech.rb create mode 100644 examples/morphology_parts_of_speech.rb create mode 100644 mock-data/request/categories.json create mode 100644 mock-data/request/entities.json create mode 100644 mock-data/request/entities_linked.json create mode 100644 mock-data/request/language.json create mode 100644 mock-data/request/morphology_complete.json create mode 100644 mock-data/request/morphology_compound_components.json create mode 100644 mock-data/request/morphology_han_readings.json create mode 100644 mock-data/request/morphology_lemmas.json create mode 100644 mock-data/request/morphology_parts_of_speech.json create mode 100644 mock-data/request/name_similarity.json create mode 100644 mock-data/request/name_translation.json create mode 100644 mock-data/request/relationships.json create mode 100644 mock-data/request/sentences.json create mode 100644 mock-data/request/sentiment.json create mode 100644 mock-data/request/tokens.json create mode 100644 parameters.rb create mode 100644 request_builder.rb create mode 100644 rosette_api.rb create mode 100644 rosette_api_error.rb create mode 100644 tests/tests.rb diff --git a/examples/categories.rb b/examples/categories.rb index eaecf30..bbb8d49 100644 --- a/examples/categories.rb +++ b/examples/categories.rb @@ -1,35 +1,15 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/categories" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/categories" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -categories_url_data = "http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/" -content = { - contentUri: categories_url_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.content_uri = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' +response = rosette_api.get_categories(params) +puts JSON.pretty_generate(response) diff --git a/examples/docker/Dockerfile b/examples/docker/Dockerfile index 1639019..eed3058 100644 --- a/examples/docker/Dockerfile +++ b/examples/docker/Dockerfile @@ -1,8 +1,15 @@ -FROM ruby:2.2.0 +FROM ruby MAINTAINER Fiona Hasanaj # install necessary software -RUN apt-get -y update && apt-get install -y vim && apt-get install -y git && gem install rubysl-securerandom +RUN apt-get -y update && apt-get install -y \ + vim \ + git + +RUN gem install rubysl-securerandom \ + rspec \ + webmock \ + simplecov RUN mkdir /ruby WORKDIR /ruby diff --git a/examples/docker/run_ruby.sh b/examples/docker/run_ruby.sh index 6b28e3d..efe2d2d 100644 --- a/examples/docker/run_ruby.sh +++ b/examples/docker/run_ruby.sh @@ -24,19 +24,6 @@ function checkAPI { fi } - -# strip the trailing slash off of the alt_url if necessary -function cleanURL() { - if [ ! -z "${ALT_URL}" ]; then - case ${ALT_URL} in - */) ALT_URL=${ALT_URL::-1} - echo "Slash detected" - ;; - esac - ping_url=${ALT_URL} - fi -} - #Checks for valid url function validateURL() { match=$(curl "${ping_url}/ping" -H "X-RosetteAPI-Key: ${API_KEY}" | grep -o "Rosette API") @@ -83,8 +70,6 @@ while getopts ":API_KEY:FILENAME:ALT_URL" arg; do esac done -cleanURL - validateURL #Copy the mounted content in /source to current WORKDIR @@ -93,7 +78,9 @@ cp -r -n /source/. . #Run the examples if [ ! -z ${API_KEY} ]; then checkAPI - cd examples + cd tests + rspec tests.rb + cd ../examples if [ ! -z ${FILENAME} ]; then runExample ${FILENAME} else diff --git a/examples/entities.rb b/examples/entities.rb index 2daead0..079ab15 100644 --- a/examples/entities.rb +++ b/examples/entities.rb @@ -1,35 +1,16 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/entities" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/entities" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -entities_text_data = "Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS" -content = { - content: entities_text_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.content = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo ' \ + 'in Boston this… http://dlvr.it/BnsFfS' +response = rosette_api.get_entities(params) +puts JSON.pretty_generate(response) diff --git a/examples/entities_linked.rb b/examples/entities_linked.rb index c1c2830..a0e2f51 100644 --- a/examples/entities_linked.rb +++ b/examples/entities_linked.rb @@ -1,35 +1,16 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/entities/linked" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/entities/linked" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -entities_linked_text_data = "Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon." -content = { - content: entities_linked_text_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including ' \ + 'Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' +response = rosette_api.get_entities_linked(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/info.rb b/examples/info.rb index e56cc03..e40bc9f 100644 --- a/examples/info.rb +++ b/examples/info.rb @@ -1,26 +1,12 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/info" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/info" + rosette_api = RosetteAPI.new(api_key, url) end - -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Get.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +response = rosette_api.info +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/language.rb b/examples/language.rb index e2560af..f6d6143 100644 --- a/examples/language.rb +++ b/examples/language.rb @@ -1,35 +1,15 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/language" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/language" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -language_data = "Por favor Señorita, says the man." -content = { - content: language_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.content = 'Por favor Señorita, says the man.?' +response = rosette_api.get_language(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_complete.rb b/examples/morphology_complete.rb index 1152aed..300db02 100644 --- a/examples/morphology_complete.rb +++ b/examples/morphology_complete.rb @@ -1,35 +1,15 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/morphology/complete" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/morphology/complete" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -morphology_complete_data = "The quick brown fox jumped over the lazy dog. Yes he did." -content = { - content: morphology_complete_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.content = 'The quick brown fox jumped over the lazy dog. Yes he did.' +response = rosette_api.get_morphology_complete(params) +puts JSON.pretty_generate(response) diff --git a/examples/morphology_compound-components.rb b/examples/morphology_compound-components.rb deleted file mode 100644 index 9d3c50b..0000000 --- a/examples/morphology_compound-components.rb +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" - -api_key, url = ARGV -raise "API Key required" unless api_key - -if !url - url = "https://api.rosette.com/rest/v1/morphology/compound-components" -else - url = url + "/morphology/compound-components" -end - -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -morphology_compound_components_data = "Rechtsschutzversicherungsgesellschaften" -content = { - content: morphology_compound_components_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) diff --git a/examples/morphology_compound_components.rb b/examples/morphology_compound_components.rb new file mode 100644 index 0000000..4d22aa1 --- /dev/null +++ b/examples/morphology_compound_components.rb @@ -0,0 +1,15 @@ +require '../rosette_api' +require '../parameters' + +api_key, url = ARGV + +if !url + rosette_api = RosetteAPI.new(api_key) +else + rosette_api = RosetteAPI.new(api_key, url) +end + +params = Parameters.new +params.content = 'Rechtsschutzversicherungsgesellschaften' +response = rosette_api.get_compound_components(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_han-readings.rb b/examples/morphology_han-readings.rb deleted file mode 100644 index 10ec439..0000000 --- a/examples/morphology_han-readings.rb +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" - -api_key, url = ARGV -raise "API Key required" unless api_key - -if !url - url = "https://api.rosette.com/rest/v1/morphology/han-readings" -else - url = url + "/morphology/han-readings" -end - -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -morphology_han_readings_data = "北京大学生物系主任办公室内部会议" -content = { - content: morphology_han_readings_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) diff --git a/examples/morphology_han_readings.rb b/examples/morphology_han_readings.rb new file mode 100644 index 0000000..4eba307 --- /dev/null +++ b/examples/morphology_han_readings.rb @@ -0,0 +1,15 @@ +require '../rosette_api' +require '../parameters' + +api_key, url = ARGV + +if !url + rosette_api = RosetteAPI.new(api_key) +else + rosette_api = RosetteAPI.new(api_key, url) +end + +params = Parameters.new +params.content = '北京大学生物系主任办公室内部会议' +response = rosette_api.get_han_readings(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_lemmas.rb b/examples/morphology_lemmas.rb index af0f7b5..3efc62e 100644 --- a/examples/morphology_lemmas.rb +++ b/examples/morphology_lemmas.rb @@ -1,35 +1,15 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/morphology/lemmas" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/morphology/lemmas" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -morphology_lemmas_data = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" -content = { - content: morphology_lemmas_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" +response = rosette_api.get_lemmas(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_parts-of-speech.rb b/examples/morphology_parts-of-speech.rb deleted file mode 100644 index 472e1db..0000000 --- a/examples/morphology_parts-of-speech.rb +++ /dev/null @@ -1,35 +0,0 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" - -api_key, url = ARGV -raise "API Key required" unless api_key - -if !url - url = "https://api.rosette.com/rest/v1/morphology/parts-of-speech" -else - url = url + "/morphology/parts-of-speech" -end - -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -morphology_parts_of_speech_data = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" -content = { - content: morphology_parts_of_speech_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) diff --git a/examples/morphology_parts_of_speech.rb b/examples/morphology_parts_of_speech.rb new file mode 100644 index 0000000..1177822 --- /dev/null +++ b/examples/morphology_parts_of_speech.rb @@ -0,0 +1,15 @@ +require '../rosette_api' +require '../parameters' + +api_key, url = ARGV + +if !url + rosette_api = RosetteAPI.new(api_key) +else + rosette_api = RosetteAPI.new(api_key, url) +end + +params = Parameters.new +params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" +response = rosette_api.get_parts_of_speech(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_similarity.rb b/examples/name_similarity.rb index 39ce09f..eda1f94 100644 --- a/examples/name_similarity.rb +++ b/examples/name_similarity.rb @@ -1,37 +1,16 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/name-similarity" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/name-similarity" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -matched_name_data1 = "Michael Jackson" -matched_name_data2 = "迈克尔·杰克逊" -names = { - name1: { text: matched_name_data1 }, - name2: { text: matched_name_data2 } -} -JSONbody = names.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.name1 = 'Michael Jackson' +params.name2 = '迈克尔·杰克逊' +response = rosette_api.name_similarity(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_translation.rb b/examples/name_translation.rb index 214c0d4..7056ea2 100644 --- a/examples/name_translation.rb +++ b/examples/name_translation.rb @@ -1,37 +1,17 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/name-translation" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/name-translation" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -translated_name_data = "معمر محمد أبو منيار القذاف" -content = { - name: translated_name_data, - targetLanguage: "eng", - targetScript: "Latn" -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.name = 'معمر محمد أبو منيار القذاف' +params.target_language = 'eng' +params.target_script = 'Latn' +response = rosette_api.name_translation(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/ping.rb b/examples/ping.rb index 98a5871..e2f7688 100644 --- a/examples/ping.rb +++ b/examples/ping.rb @@ -1,26 +1,12 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/ping" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/ping" + rosette_api = RosetteAPI.new(api_key, url) end - -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Get.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +response = rosette_api.ping +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/relationships.rb b/examples/relationships.rb index acd69d5..6d64ca0 100644 --- a/examples/relationships.rb +++ b/examples/relationships.rb @@ -1,35 +1,15 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/relationships" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/relationships" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -relationships_text_data = "The Ghostbusters movie was filmed in Boston." -content = { - content: relationships_text_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.content = 'The Ghostbusters movie was filmed in Boston.' +response = rosette_api.get_relationships(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/sentences.rb b/examples/sentences.rb index e0b2b48..dd997b8 100644 --- a/examples/sentences.rb +++ b/examples/sentences.rb @@ -1,35 +1,18 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/sentences" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/sentences" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -sentences_data = "This land is your land. This land is my land\nFrom California to the New York island;\nFrom the red wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was walking that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that golden valley:\nThis land was made for you and me." -content = { - content: sentences_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.content = 'This land is your land. This land is my land\nFrom California to the New York island;\nFrom the' \ + ' wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was walking' \ + ' that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that' \ + ' golden valley:\nThis land was made for you and me.' +response = rosette_api.get_sentences(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/sentiment.rb b/examples/sentiment.rb index c6b3132..39815f5 100644 --- a/examples/sentiment.rb +++ b/examples/sentiment.rb @@ -1,55 +1,25 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" require 'tempfile' -require 'securerandom' +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/sentiment" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/sentiment" + rosette_api = RosetteAPI.new(api_key, url) end -file = Tempfile.new(['foo', '.html']) -sentiment_text_data ="New Ghostbusters Film

Original Ghostbuster Dan Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new all-female Ghostbusters cast, telling The Hollywood Reporter, The Aykroyd family is delighted by this inheritance of the Ghostbusters torch by these most magnificent women in comedy.

" +params = Parameters.new +file = Tempfile.new(%w(foo .html)) +sentiment_text_data = 'New Ghostbusters Film

Original Ghostbuster Dan ' \ + 'Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new ' \ + 'all-female Ghostbusters cast, telling The Hollywood Reporter, The Aykroyd family is delighted ' \ + 'by this inheritance of the Ghostbusters torch by these most magnificent women in comedy ' \ + '.

' file.write(sentiment_text_data) -file.open -request_file = {:language => "eng"} - -uri = URI.parse(url) -BOUNDARY = SecureRandom.hex -post_body = [] - -# Add the content data -post_body << "--#{BOUNDARY}\r\n" -post_body << "Content-Disposition: form-data; name=\"content\"; filename=\"#{File.basename(file)}\"\r\n" -post_body << "Content-Type: text/plain\r\n\r\n" -post_body << file.read - -# Add the request data -post_body << "\r\n\r\n--#{BOUNDARY}\r\n" -post_body << "Content-Disposition: form-data; name=\"request\"\r\n" -post_body << "Content-Type: application/json\r\n\r\n" -post_body << request_file.to_json -post_body << "\r\n\r\n--#{BOUNDARY}--\r\n" - -# Create the HTTP objects -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' -request = Net::HTTP::Post.new(uri.request_uri) -request.add_field("Content-Type", "multipart/form-data; boundary=#{BOUNDARY}") -request.add_field("X-RosetteAPI-Key", api_key) -request.body = post_body.join - -# Send the request -response = http.request(request) -response_headers = {} -response.header.each_header {|key,value| response_headers[key] = value} -response_headers = {"responseHeaders" => response_headers} -puts JSON.pretty_generate(JSON.parse(response.body).merge(response_headers)) \ No newline at end of file +file.close +params.file_path = file.path +params.language = 'eng' +response = rosette_api.get_sentiment(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/tokens.rb b/examples/tokens.rb index 0258f52..35c11f4 100644 --- a/examples/tokens.rb +++ b/examples/tokens.rb @@ -1,35 +1,15 @@ -#!/usr/bin/env ruby -# encoding: utf-8 - -require "net/http" -require "net/https" -require "json" +require '../rosette_api' +require '../parameters' api_key, url = ARGV -raise "API Key required" unless api_key if !url - url = "https://api.rosette.com/rest/v1/tokens" + rosette_api = RosetteAPI.new(api_key) else - url = url + "/tokens" + rosette_api = RosetteAPI.new(api_key, url) end -uri = URI.parse(url) -http = Net::HTTP.new(uri.host, uri.port) -http.use_ssl = true if uri.scheme == 'https' - -request = Net::HTTP::Post.new(uri.request_uri) -request["X-RosetteAPI-Key"] = api_key -request["Content-Type"] = "application/json" -request["Accept"] = "application/json" -tokens_data = "北京大学生物系主任办公室内部会议" -content = { - content: tokens_data -} -JSONbody = content.to_json - -request.body = JSONbody - -response = http.request(request) - -puts JSON.pretty_generate(JSON.parse(response.body)) +params = Parameters.new +params.content = '北京大学生物系主任办公室内部会议' +response = rosette_api.get_tokens(params) +puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/mock-data/request/categories.json b/mock-data/request/categories.json new file mode 100644 index 0000000..74548df --- /dev/null +++ b/mock-data/request/categories.json @@ -0,0 +1 @@ +{"contentUri":"http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/"} \ No newline at end of file diff --git a/mock-data/request/entities.json b/mock-data/request/entities.json new file mode 100644 index 0000000..c3f2150 --- /dev/null +++ b/mock-data/request/entities.json @@ -0,0 +1 @@ +{"content":"Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS"} \ No newline at end of file diff --git a/mock-data/request/entities_linked.json b/mock-data/request/entities_linked.json new file mode 100644 index 0000000..8027d1c --- /dev/null +++ b/mock-data/request/entities_linked.json @@ -0,0 +1 @@ +{"content":"Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon."} \ No newline at end of file diff --git a/mock-data/request/language.json b/mock-data/request/language.json new file mode 100644 index 0000000..e7cafb2 --- /dev/null +++ b/mock-data/request/language.json @@ -0,0 +1 @@ +{"content":"Por favor Senorita, says the man.?"} \ No newline at end of file diff --git a/mock-data/request/morphology_complete.json b/mock-data/request/morphology_complete.json new file mode 100644 index 0000000..e6c83eb --- /dev/null +++ b/mock-data/request/morphology_complete.json @@ -0,0 +1 @@ +{"content":"The quick brown fox jumped over the lazy dog. Yes he did."} \ No newline at end of file diff --git a/mock-data/request/morphology_compound_components.json b/mock-data/request/morphology_compound_components.json new file mode 100644 index 0000000..4e436e8 --- /dev/null +++ b/mock-data/request/morphology_compound_components.json @@ -0,0 +1 @@ +{"content":"Rechtsschutzversicherungsgesellschaften"} \ No newline at end of file diff --git a/mock-data/request/morphology_han_readings.json b/mock-data/request/morphology_han_readings.json new file mode 100644 index 0000000..8060d2e --- /dev/null +++ b/mock-data/request/morphology_han_readings.json @@ -0,0 +1 @@ +{"content":"北京大学生物系主任办公室内部会议"} \ No newline at end of file diff --git a/mock-data/request/morphology_lemmas.json b/mock-data/request/morphology_lemmas.json new file mode 100644 index 0000000..a84a11d --- /dev/null +++ b/mock-data/request/morphology_lemmas.json @@ -0,0 +1 @@ +{"content":"The fact is that the geese just went back to get a rest and I'm not banking on their return soon"} \ No newline at end of file diff --git a/mock-data/request/morphology_parts_of_speech.json b/mock-data/request/morphology_parts_of_speech.json new file mode 100644 index 0000000..a84a11d --- /dev/null +++ b/mock-data/request/morphology_parts_of_speech.json @@ -0,0 +1 @@ +{"content":"The fact is that the geese just went back to get a rest and I'm not banking on their return soon"} \ No newline at end of file diff --git a/mock-data/request/name_similarity.json b/mock-data/request/name_similarity.json new file mode 100644 index 0000000..7722333 --- /dev/null +++ b/mock-data/request/name_similarity.json @@ -0,0 +1 @@ +{"name1":"Michael Jackson","name2":"迈克尔·杰克逊"} \ No newline at end of file diff --git a/mock-data/request/name_translation.json b/mock-data/request/name_translation.json new file mode 100644 index 0000000..91704eb --- /dev/null +++ b/mock-data/request/name_translation.json @@ -0,0 +1 @@ +{"name":"معمر محمد أبو منيار القذاف","targetLanguage":"eng","targetScript":"Latn"} \ No newline at end of file diff --git a/mock-data/request/relationships.json b/mock-data/request/relationships.json new file mode 100644 index 0000000..011595c --- /dev/null +++ b/mock-data/request/relationships.json @@ -0,0 +1 @@ +{"content":"The Ghostbusters movie was filmed in Boston."} \ No newline at end of file diff --git a/mock-data/request/sentences.json b/mock-data/request/sentences.json new file mode 100644 index 0000000..ec32d53 --- /dev/null +++ b/mock-data/request/sentences.json @@ -0,0 +1 @@ +{"content":"This land is your land. This land is my land\\nFrom California to the New York island;\\nFrom the wood forest to the Gulf Stream waters\\n\\nThis land was made for you and Me.\\n\\nAs I was walking that ribbon of highway,\\nI saw above me that endless skyway:\\nI saw below me that golden valley:\\nThis land was made for you and me."} \ No newline at end of file diff --git a/mock-data/request/sentiment.json b/mock-data/request/sentiment.json new file mode 100644 index 0000000..2cbc3ad --- /dev/null +++ b/mock-data/request/sentiment.json @@ -0,0 +1 @@ +{"content":"New Ghostbusters Film

Original Ghostbuster Dan Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new all-female Ghostbusters cast, telling The Hollywood Reporter, The Aykroyd family is delighted by this inheritance of the Ghostbusters torch by these most magnificent women in comedy.

"} \ No newline at end of file diff --git a/mock-data/request/tokens.json b/mock-data/request/tokens.json new file mode 100644 index 0000000..8060d2e --- /dev/null +++ b/mock-data/request/tokens.json @@ -0,0 +1 @@ +{"content":"北京大学生物系主任办公室内部会议"} \ No newline at end of file diff --git a/parameters.rb b/parameters.rb new file mode 100644 index 0000000..1d2aee3 --- /dev/null +++ b/parameters.rb @@ -0,0 +1,68 @@ +require_relative 'rosette_api_error' + +class Parameters + + attr_accessor :content, :content_uri, :language, :entity_type, :name, :source_language_of_origin, + :source_language_of_use, :source_script, :target_language, :target_scheme, :target_script, :name1, + :name2, :file_path + + def initialize + #general + @content = nil + @content_uri = nil + @file_path = nil + @language = nil + #name-translation + @entity_type = nil + @name = nil + @source_language_of_origin = nil + @source_language_of_use = nil + @source_script = nil + @target_language = nil + @target_scheme = nil + @target_script = nil + #name-similarity + @name1 = nil + @name2 = nil + end + + def to_hash + hash = {} + instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } + hash + end + + def validate_params + if [@content, @content_uri, @file_path].count { |attr| !attr.nil? } > 1 + raise RosetteAPIError.new(400, 'The format of the request is invalid: multiple content sources;' \ + ' must be one of an attachment, an inline "content" field, or an external "contentUri"') + elsif [@content, @content_uri, @file_path].count { |attr| attr.nil? } == 3 && [@name, @name1, @name2].count { |attr| attr.nil? } > 0 + raise RosetteAPIError.new(400, 'The format of the request is invalid: no content provided; must' \ + ' be one of an attachment, an inline "content" field, or an external "contentUri"') + else + load_params + end + end + + def validate_name_similarity_params + if @name1.nil? + raise RosetteAPIError.new(400, 'The format of the request is invalid: invalid options: name1 may not be null') + elsif name2.nil? + raise RosetteAPIError.new(400, 'The format of the request is invalid: invalid options: name2 may not be null') + else + load_params + end + end + + def validate_name_translation_params + if @name.nil? + raise RosetteAPIError.new(400, 'The format of the request is invalid: invalid options: name: may not be null') + else + load_params + end + end + + def load_params + self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h + end +end \ No newline at end of file diff --git a/request_builder.rb b/request_builder.rb new file mode 100644 index 0000000..822aaca --- /dev/null +++ b/request_builder.rb @@ -0,0 +1,112 @@ +require 'net/http' +require 'net/https' +require 'json' +require 'securerandom' +require_relative 'rosette_api_error' +require_relative 'parameters' + +class RequestBuilder + attr_reader :user_key, :alternate_url, :params + + def initialize(user_key, alternate_url, params={}) + @user_key = user_key + @alternate_url = alternate_url + @params = params + end + + def prepare_plain_request(params) + uri = URI.parse(@alternate_url) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true if uri.scheme == 'https' + + request = Net::HTTP::Post.new(uri.request_uri) + request['X-RosetteAPI-Key'] = @user_key + request['Content-Type'] = 'application/json' + request['Accept'] = 'application/json' + request.body = params.to_json + + [http, request] + end + + def prepare_multipart_request(params) + begin + file = File.open(params['filePath'], 'r') + text = file.read + rescue => err + raise err + end + + boundary = SecureRandom.hex + post_body = [] + request_file = params.to_json + + # Add the content data + post_body << "--#{boundary}\r\n" + post_body << "Content-Disposition: form-data; name=\"content\"; filename=\"#{File.basename(file)}\"\r\n" + post_body << "Content-Type: text/plain\r\n\r\n" + post_body << text + + # Add the request data + post_body << "\r\n\r\n--#{boundary}\r\n" + post_body << "Content-Disposition: form-data; name=\"request\"\r\n" + post_body << "Content-Type: application/json\r\n\r\n" + post_body << request_file + post_body << "\r\n\r\n--#{boundary}--\r\n" + + # Create the HTTP objects + uri = URI.parse(@alternate_url) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true if uri.scheme == 'https' + request = Net::HTTP::Post.new(uri.request_uri) + request.add_field('Content-Type', "multipart/form-data; boundary=#{boundary}") + request.add_field('X-RosetteAPI-Key', @user_key) + request.body = post_body.join + + [http, request] + end + + def send_get_request + uri = URI.parse(@alternate_url) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = true if uri.scheme == 'https' + + request = Net::HTTP::Get.new(uri.request_uri) + request['X-RosetteAPI-Key'] = @user_key + + get_response(http, request) + end + + def send_post_request + if @alternate_url.to_s.include? '/info?clientVersion=' + params = '{"body": "version check"}' + else + params = @params + end + + if !params['filePath'].nil? + http, request = prepare_multipart_request(params) + else + http, request = prepare_plain_request(params) + end + + get_response(http, request) + end + + def get_response(http, request) + response = http.request(request) + if response.code != '200' + message = + if JSON.parse(response.body)['message'].nil? + response.body + else + JSON.parse(response.body)['message'] + end + raise RosetteAPIError.new(response.code, message) + else + response_headers = {} + response.header.each_header { |key, value| response_headers[key] = value } + response_headers = {:responseHeaders => response_headers} + JSON.parse(response.body).merge(response_headers) + end + end +end \ No newline at end of file diff --git a/rosette_api.rb b/rosette_api.rb new file mode 100644 index 0000000..2699ba9 --- /dev/null +++ b/rosette_api.rb @@ -0,0 +1,122 @@ +require_relative 'request_builder' + +class RosetteAPI + BINDING_VERSION = '1.0.2' + LANGUAGE_ENDPOINT = '/language' + MORPHOLOGY_ENDPOINT = '/morphology' + ENTITIES_ENDPOINT = '/entities' + ENTITIES_LINKED_ENDPOINT= '/entities/linked' + CATEGORIES_ENDPOINT = '/categories' + RELATIONSHIPS_ENDPOINT = '/relationships' + SENTIMENT_ENDPOINT = '/sentiment' + NAME_TRANSLATION_ENDPOINT = '/name-translation' + NAME_SIMILARITY_ENDPOINT = '/name-similarity' + TOKENS_ENDPOINT = '/tokens' + SENTENCES_ENDPOINT = '/sentences' + INFO = '/info' + VERSION_CHECK = '/info?clientVersion=' + BINDING_VERSION + PING = '/ping' + + attr_accessor :user_key, :alternate_url + + def initialize(user_key, alternate_url='https://api.rosette.com/rest/v1') + @user_key = user_key + @alternate_url = alternate_url + if @alternate_url.to_s.end_with?('/') + @alternate_url = alternate_url.to_s.slice(0..-2) + end + check_version_compatibility + end + + def check_version_compatibility + response = RequestBuilder.new(@user_key, @alternate_url + VERSION_CHECK).send_post_request + unless response['versionChecked'] + puts JSON.pretty_generate(response) + exit + end + end + + def get_language(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + LANGUAGE_ENDPOINT, params).send_post_request + end + + def get_morphology_complete(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/complete', params).send_post_request + end + + def get_compound_components(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url +MORPHOLOGY_ENDPOINT + '/compound-components', params) + .send_post_request + end + + def get_han_readings(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/han-readings', params).send_post_request + end + + def get_lemmas(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/lemmas', params).send_post_request + end + + def get_parts_of_speech(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/parts-of-speech', params).send_post_request + end + + def get_entities(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + ENTITIES_ENDPOINT, params).send_post_request + end + + def get_entities_linked(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + ENTITIES_LINKED_ENDPOINT, params).send_post_request + end + + def get_categories(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + CATEGORIES_ENDPOINT, params).send_post_request + end + + def get_relationships(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + RELATIONSHIPS_ENDPOINT, params).send_post_request + end + + def get_sentiment(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + SENTIMENT_ENDPOINT, params).send_post_request + end + + def name_translation(params) + params = params.validate_name_translation_params + RequestBuilder.new(@user_key, @alternate_url + NAME_TRANSLATION_ENDPOINT, params).send_post_request + end + + def name_similarity(params) + params = params.validate_name_similarity_params + RequestBuilder.new(@user_key, @alternate_url + NAME_SIMILARITY_ENDPOINT, params).send_post_request + end + + def get_tokens(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + TOKENS_ENDPOINT, params).send_post_request + end + + def get_sentences(params) + params = params.validate_params + RequestBuilder.new(@user_key, @alternate_url + SENTENCES_ENDPOINT, params).send_post_request + end + + def info + RequestBuilder.new(@user_key, @alternate_url + INFO).send_get_request + end + + def ping + RequestBuilder.new(@user_key, @alternate_url + PING).send_get_request + end +end \ No newline at end of file diff --git a/rosette_api_error.rb b/rosette_api_error.rb new file mode 100644 index 0000000..ca3857f --- /dev/null +++ b/rosette_api_error.rb @@ -0,0 +1,8 @@ +class RosetteAPIError < StandardError + attr_accessor :status_code, :message + + def initialize(status_code, message) + @status_code = status_code + @message = message + end +end \ No newline at end of file diff --git a/tests/tests.rb b/tests/tests.rb new file mode 100644 index 0000000..ae11897 --- /dev/null +++ b/tests/tests.rb @@ -0,0 +1,486 @@ +# encoding: UTF-8 +require_relative '../rosette_api' +require 'rspec' +require 'webmock/rspec' +require 'json' +WebMock.disable_net_connect!(:allow_localhost => true) + +describe RosetteAPI do + + describe '.get_language' do + request_file = File.open('../mock-data/request/language.json') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/language'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'language'}.to_json, :headers => {}) + end + it 'test language' do + params = Parameters.new + params.content = 'Por favor Senorita, says the man.?' + response = RosetteAPI.new('0123456789').get_language(params) + expect(response).instance_of? Hash + end + + it 'badRequestFormat: the format of the request is invalid: multiple content sources' do + params = Parameters.new + params.content = 'Por favor Senorita, says the man.?' + params.content_uri = 'Por favor Senorita, says the man.?' + expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(RosetteAPIError) + end + + it 'badRequestFormat: the format of the request is invalid: no content provided;' do + params = Parameters.new + expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(RosetteAPIError) + end + end + + describe '.get_morphology_complete' do + request_file = File.open('../mock-data/request/morphology_complete.json') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/complete'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'morphology/complete'}.to_json, :headers => {}) + end + it 'test morphology complete' do + params = Parameters.new + params.content = 'The quick brown fox jumped over the lazy dog. Yes he did.' + response = RosetteAPI.new('0123456789').get_morphology_complete(params) + expect(response).instance_of? Hash + end + end + + describe '.get_compound_components' do + request_file = File.open('../mock-data/request/morphology_compound_components.json') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/compound-components'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'morphology/compound-components'}.to_json, :headers => {}) + end + it 'test morphology compound components' do + params = Parameters.new + params.content = 'Rechtsschutzversicherungsgesellschaften' + response = RosetteAPI.new('0123456789').get_compound_components(params) + expect(response).instance_of? Hash + end + end + + describe '.get_han_readings' do + request_file = File.open('../mock-data/request/morphology_han_readings.json', :encoding => 'utf-8') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/han-readings'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'morphology/han-readings'}.to_json, :headers => {}) + end + it 'test morphology han readings' do + params = Parameters.new + params.content = '北京大学生物系主任办公室内部会议' + response = RosetteAPI.new('0123456789').get_han_readings(params) + expect(response).instance_of? Hash + end + end + + describe '.get_parts_of_speech' do + request_file = File.open('../mock-data/request/morphology_parts_of_speech.json') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/parts-of-speech'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'morphology/parts-of-speech'}.to_json, :headers => {}) + end + it 'test morphology parts of speech' do + params = Parameters.new + params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" + response = RosetteAPI.new('0123456789').get_parts_of_speech(params) + expect(response).instance_of? Hash + end + end + + describe '.get_lemmas' do + request_file = File.open('../mock-data/request/morphology_lemmas.json') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/lemmas'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'morphology/lemmas'}.to_json, :headers => {}) + end + it 'test morphology lemmas' do + params = Parameters.new + params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" + response = RosetteAPI.new('0123456789').get_lemmas(params) + expect(response).instance_of? Hash + end + end + + describe '.get_entities' do + request_file = File.open('../mock-data/request/entities.json', :encoding => 'utf-8') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/entities'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'entities'}.to_json, :headers => {}) + end + it 'test entities' do + params = Parameters.new + params.content = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a' \ + ' cameo in Boston this… http://dlvr.it/BnsFfS' + response = RosetteAPI.new('0123456789').get_entities(params) + expect(response).instance_of? Hash + end + end + + describe '.get_entities_linked' do + request_file = File.open('../mock-data/request/entities_linked.json') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/entities/linked'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'entities/linked'}.to_json, :headers => {}) + end + it 'test entities linked' do + params = Parameters.new + params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including' \ + ' Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' + response = RosetteAPI.new('0123456789').get_entities_linked(params) + expect(response).instance_of? Hash + end + end + + describe '.get_categories' do + request_file = File.open('../mock-data/request/categories.json') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/categories'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'categories'}.to_json, :headers => {}) + end + it 'test categories' do + params = Parameters.new + params.content_uri = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' + response = RosetteAPI.new('0123456789').get_categories(params) + expect(response).instance_of? Hash + end + end + + describe '.get_relationships' do + request_file = File.open('../mock-data/request/relationships.json') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/relationships'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'relationships'}.to_json, :headers => {}) + end + it 'test relationships' do + params = Parameters.new + params.content = 'The Ghostbusters movie was filmed in Boston.' + response = RosetteAPI.new('0123456789').get_relationships(params) + expect(response).instance_of? Hash + end + end + + describe '.name_translation' do + request_file = File.open('../mock-data/request/name_translation.json', :encoding => 'utf-8') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/name-translation'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'name-translation'}.to_json, :headers => {}) + end + it 'test name translation' do + params = Parameters.new + params.name = 'معمر محمد أبو منيار القذاف'.encode('UTF-8') + params.target_language = 'eng' + params.target_script = 'Latn' + response = RosetteAPI.new('0123456789').name_translation(params) + expect(response).instance_of? Hash + end + + it 'badRequestFormat: needs to provide name parameter' do + params = Parameters.new + params.target_language = 'eng' + params.target_script = 'Latn' + expect { RosetteAPI.new('0123456789').name_translation(params) }.to raise_error(RosetteAPIError) + end + end + + describe '.name_similarity' do + request_file = File.open('../mock-data/request/name_similarity.json', :encoding => 'utf-8') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/name-similarity'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'name-similarity'}.to_json, :headers => {}) + end + it 'test name similarity' do + params = Parameters.new + params.name1 = 'Michael Jackson' + params.name2 = '迈克尔·杰克逊' + response = RosetteAPI.new('0123456789').name_similarity(params) + expect(response).instance_of? Hash + end + + it 'badRequestFormat: needs to provide name1 parameter' do + params = Parameters.new + params.name2 = 'Michael Jackson' + expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) + end + + it 'badRequestFormat: needs to provide name2 parameter' do + params = Parameters.new + params.name1 = 'Michael Jackson' + expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) + end + end + + describe '.get_tokens' do + request_file = File.open('../mock-data/request/tokens.json', :encoding => 'utf-8') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/tokens'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'tokens'}.to_json, :headers => {}) + end + it 'test tokens' do + params = Parameters.new + params.content = '北京大学生物系主任办公室内部会议' + response = RosetteAPI.new('0123456789').get_tokens(params) + expect(response).instance_of? Hash + end + end + + describe '.get_sentences' do + request_file = File.open('../mock-data/request/sentences.json') + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/sentences'). + with(:body => request_file.read, + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'sentences'}.to_json, :headers => {}) + end + it 'test sentences' do + params = Parameters.new + params.content = 'This land is your land. This land is my land\nFrom California to the New York island;\nFrom' \ + ' the wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was' \ + ' walking that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that' \ + ' golden valley:\nThis land was made for you and me.' + response = RosetteAPI.new('0123456789').get_sentences(params) + expect(response).instance_of? Hash + end + end + + describe '.info' do + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:get, 'https://api.rosette.com/rest/v1/info'). + with(:headers => {'Accept' => '*/*', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'info'}.to_json, :headers => {}) + end + it 'test info' do + response = RosetteAPI.new('0123456789').info + expect(response).instance_of? Hash + end + end + + describe '.ping' do + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", + :headers => {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + stub_request(:get, 'https://api.rosette.com/rest/v1/ping'). + with(:headers => {'Accept' => '*/*', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(:status => 200, :body => {'test': 'ping'}.to_json, :headers => {}) + end + it 'test ping' do + response = RosetteAPI.new('0123456789').ping + expect(response).instance_of? Hash + end + end +end From 5225da88c7c9dc1218d0738dcf1d66a1cf574e2e Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 15 Apr 2016 15:34:41 -0400 Subject: [PATCH 03/42] Split parameters class. Improved error handling and typecheck --- document_parameters.rb | 32 ++++++ examples/categories.rb | 4 +- examples/entities.rb | 4 +- examples/entities_linked.rb | 4 +- examples/language.rb | 4 +- examples/morphology_complete.rb | 4 +- examples/morphology_compound_components.rb | 4 +- examples/morphology_han_readings.rb | 4 +- examples/morphology_lemmas.rb | 4 +- examples/morphology_parts_of_speech.rb | 4 +- examples/name_similarity.rb | 8 +- examples/name_translation.rb | 4 +- examples/relationships.rb | 4 +- examples/sentences.rb | 4 +- examples/sentiment.rb | 4 +- examples/tokens.rb | 4 +- name_similarity_parameters.rb | 33 ++++++ name_translation_parameters.rb | 32 ++++++ parameters.rb | 2 +- rosette_api.rb | 126 ++++++++++++++++----- tests/tests.rb | 42 +++---- 21 files changed, 246 insertions(+), 85 deletions(-) create mode 100644 document_parameters.rb create mode 100644 name_similarity_parameters.rb create mode 100644 name_translation_parameters.rb diff --git a/document_parameters.rb b/document_parameters.rb new file mode 100644 index 0000000..894f81b --- /dev/null +++ b/document_parameters.rb @@ -0,0 +1,32 @@ +require_relative 'rosette_api_error' +class DocumentParameters + attr_accessor :content, :content_uri, :file_path, :language + + def initialize + @content = nil + @content_uri = nil + @file_path = nil + @language = nil + end + + def validate_params + if [@content, @content_uri, @file_path].count { |attr| !attr.nil? } > 1 + raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: multiple content sources;' \ + ' must be one of an attachment, an inline "content" field, or an external "contentUri"') + elsif [@content, @content_uri, @file_path].count { |attr| attr.nil? } == 3 + raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: no content provided; must' \ + ' be one of an attachment, an inline "content" field, or an external "contentUri"') + end + end + + def load_params + validate_params + self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h + end + + def to_hash + hash = {} + instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } + hash + end +end \ No newline at end of file diff --git a/examples/categories.rb b/examples/categories.rb index bbb8d49..8083b60 100644 --- a/examples/categories.rb +++ b/examples/categories.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content_uri = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' response = rosette_api.get_categories(params) puts JSON.pretty_generate(response) diff --git a/examples/entities.rb b/examples/entities.rb index 079ab15..f36dd61 100644 --- a/examples/entities.rb +++ b/examples/entities.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo ' \ 'in Boston this… http://dlvr.it/BnsFfS' response = rosette_api.get_entities(params) diff --git a/examples/entities_linked.rb b/examples/entities_linked.rb index a0e2f51..73668a7 100644 --- a/examples/entities_linked.rb +++ b/examples/entities_linked.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including ' \ 'Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' response = rosette_api.get_entities_linked(params) diff --git a/examples/language.rb b/examples/language.rb index f6d6143..dc83754 100644 --- a/examples/language.rb +++ b/examples/language.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = 'Por favor Señorita, says the man.?' response = rosette_api.get_language(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_complete.rb b/examples/morphology_complete.rb index 300db02..ec50486 100644 --- a/examples/morphology_complete.rb +++ b/examples/morphology_complete.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = 'The quick brown fox jumped over the lazy dog. Yes he did.' response = rosette_api.get_morphology_complete(params) puts JSON.pretty_generate(response) diff --git a/examples/morphology_compound_components.rb b/examples/morphology_compound_components.rb index 4d22aa1..698fb4e 100644 --- a/examples/morphology_compound_components.rb +++ b/examples/morphology_compound_components.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = 'Rechtsschutzversicherungsgesellschaften' response = rosette_api.get_compound_components(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_han_readings.rb b/examples/morphology_han_readings.rb index 4eba307..57d1f7d 100644 --- a/examples/morphology_han_readings.rb +++ b/examples/morphology_han_readings.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = '北京大学生物系主任办公室内部会议' response = rosette_api.get_han_readings(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_lemmas.rb b/examples/morphology_lemmas.rb index 3efc62e..5fdb4df 100644 --- a/examples/morphology_lemmas.rb +++ b/examples/morphology_lemmas.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" response = rosette_api.get_lemmas(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_parts_of_speech.rb b/examples/morphology_parts_of_speech.rb index 1177822..ffc2c09 100644 --- a/examples/morphology_parts_of_speech.rb +++ b/examples/morphology_parts_of_speech.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" response = rosette_api.get_parts_of_speech(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_similarity.rb b/examples/name_similarity.rb index eda1f94..7b0de74 100644 --- a/examples/name_similarity.rb +++ b/examples/name_similarity.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../name_similarity_parameters' api_key, url = ARGV @@ -9,8 +9,8 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new -params.name1 = 'Michael Jackson' -params.name2 = '迈克尔·杰克逊' +params = NameSimilarityParameters.new +params.name1 = {:text => 'Michael Jackson', :language => 'eng', :entityType => 'PERSON'} +params.name2 = {:text => '迈克尔·杰克逊', :entityType => 'PERSON'} response = rosette_api.name_similarity(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_translation.rb b/examples/name_translation.rb index 7056ea2..5fb5c1f 100644 --- a/examples/name_translation.rb +++ b/examples/name_translation.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../name_translation_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = NameTranslationParameters.new params.name = 'معمر محمد أبو منيار القذاف' params.target_language = 'eng' params.target_script = 'Latn' diff --git a/examples/relationships.rb b/examples/relationships.rb index 6d64ca0..a198153 100644 --- a/examples/relationships.rb +++ b/examples/relationships.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = 'The Ghostbusters movie was filmed in Boston.' response = rosette_api.get_relationships(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/sentences.rb b/examples/sentences.rb index dd997b8..7077eb8 100644 --- a/examples/sentences.rb +++ b/examples/sentences.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = 'This land is your land. This land is my land\nFrom California to the New York island;\nFrom the' \ ' wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was walking' \ ' that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that' \ diff --git a/examples/sentiment.rb b/examples/sentiment.rb index 39815f5..08ce3c8 100644 --- a/examples/sentiment.rb +++ b/examples/sentiment.rb @@ -1,6 +1,6 @@ require 'tempfile' require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -10,7 +10,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new file = Tempfile.new(%w(foo .html)) sentiment_text_data = 'New Ghostbusters Film

Original Ghostbuster Dan ' \ 'Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new ' \ diff --git a/examples/tokens.rb b/examples/tokens.rb index 35c11f4..d40b599 100644 --- a/examples/tokens.rb +++ b/examples/tokens.rb @@ -1,5 +1,5 @@ require '../rosette_api' -require '../parameters' +require '../document_parameters' api_key, url = ARGV @@ -9,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = Parameters.new +params = DocumentParameters.new params.content = '北京大学生物系主任办公室内部会议' response = rosette_api.get_tokens(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/name_similarity_parameters.rb b/name_similarity_parameters.rb new file mode 100644 index 0000000..f8588db --- /dev/null +++ b/name_similarity_parameters.rb @@ -0,0 +1,33 @@ +class NameSimilarityParameters + attr_accessor :name1, :name2 + + def initialize + @name1 = nil + @name2 = nil + end + + def validate_params + if @name1.nil? + raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: invalid options: name1' \ + ' not be null.') + elsif [String, Hash].count { |clazz| @name1.instance_of? clazz } == 0 + raise RosetteAPIError.new('badRequest', 'name1 option can only be an instance of a String or Hash') + elsif @name2.nil? + raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: invalid options: name2' \ + ' may not be null') + elsif [String, Hash].count { |clazz| @name2.instance_of? clazz } == 0 + raise RosetteAPIError.new('badRequest', 'name2 option can only be an instance of a String or Hash') + end + end + + def load_params + validate_params + self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h + end + + def to_hash + hash = {} + instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } + hash + end +end \ No newline at end of file diff --git a/name_translation_parameters.rb b/name_translation_parameters.rb new file mode 100644 index 0000000..0101643 --- /dev/null +++ b/name_translation_parameters.rb @@ -0,0 +1,32 @@ +class NameTranslationParameters + attr_accessor :entity_type, :name, :source_language_of_origin, :source_language_of_use, :source_script, + :target_language, :target_scheme, :target_script + + def initialize + @entity_type = nil + @name = nil + @source_language_of_origin = nil + @source_language_of_use = nil + @source_script = nil + @target_language = nil + @target_scheme = nil + @target_script = nil + end + + def validate_params + if @name.nil? + raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: invalid options: name: may not be null') + end + end + + def load_params + validate_params + self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h + end + + def to_hash + hash = {} + instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } + hash + end +end \ No newline at end of file diff --git a/parameters.rb b/parameters.rb index 1d2aee3..b080f0b 100644 --- a/parameters.rb +++ b/parameters.rb @@ -47,7 +47,7 @@ def validate_params def validate_name_similarity_params if @name1.nil? raise RosetteAPIError.new(400, 'The format of the request is invalid: invalid options: name1 may not be null') - elsif name2.nil? + elsif @name2.nil? raise RosetteAPIError.new(400, 'The format of the request is invalid: invalid options: name2 may not be null') else load_params diff --git a/rosette_api.rb b/rosette_api.rb index 2699ba9..4aae6f1 100644 --- a/rosette_api.rb +++ b/rosette_api.rb @@ -1,4 +1,8 @@ require_relative 'request_builder' +require_relative 'document_parameters' +require_relative 'name_translation_parameters' +require_relative 'name_similarity_parameters' +require_relative 'rosette_api_error' class RosetteAPI BINDING_VERSION = '1.0.2' @@ -37,79 +41,139 @@ def check_version_compatibility end def get_language(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + LANGUAGE_ENDPOINT, params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + LANGUAGE_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_morphology_complete(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/complete', params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/complete', params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_compound_components(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url +MORPHOLOGY_ENDPOINT + '/compound-components', params) - .send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url +MORPHOLOGY_ENDPOINT + '/compound-components', params) + .send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_han_readings(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/han-readings', params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/han-readings', params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_lemmas(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/lemmas', params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/lemmas', params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_parts_of_speech(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/parts-of-speech', params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/parts-of-speech', params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_entities(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + ENTITIES_ENDPOINT, params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + ENTITIES_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_entities_linked(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + ENTITIES_LINKED_ENDPOINT, params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + ENTITIES_LINKED_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_categories(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + CATEGORIES_ENDPOINT, params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + CATEGORIES_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_relationships(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + RELATIONSHIPS_ENDPOINT, params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + RELATIONSHIPS_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_sentiment(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + SENTIMENT_ENDPOINT, params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + SENTIMENT_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def name_translation(params) - params = params.validate_name_translation_params - RequestBuilder.new(@user_key, @alternate_url + NAME_TRANSLATION_ENDPOINT, params).send_post_request + if params.instance_of? NameTranslationParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + NAME_TRANSLATION_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a NameTranslationParameters type as an argument') + end end def name_similarity(params) - params = params.validate_name_similarity_params - RequestBuilder.new(@user_key, @alternate_url + NAME_SIMILARITY_ENDPOINT, params).send_post_request + if params.instance_of? NameSimilarityParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + NAME_SIMILARITY_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a NameSimilarityParameters type as an argument') + end end def get_tokens(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + TOKENS_ENDPOINT, params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + TOKENS_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def get_sentences(params) - params = params.validate_params - RequestBuilder.new(@user_key, @alternate_url + SENTENCES_ENDPOINT, params).send_post_request + if params.instance_of? DocumentParameters + params = params.load_params + RequestBuilder.new(@user_key, @alternate_url + SENTENCES_ENDPOINT, params).send_post_request + else + raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') + end end def info diff --git a/tests/tests.rb b/tests/tests.rb index ae11897..caed296 100644 --- a/tests/tests.rb +++ b/tests/tests.rb @@ -28,14 +28,14 @@ to_return(:status => 200, :body => {'test': 'language'}.to_json, :headers => {}) end it 'test language' do - params = Parameters.new + params = DocumentParameters.new params.content = 'Por favor Senorita, says the man.?' response = RosetteAPI.new('0123456789').get_language(params) expect(response).instance_of? Hash end it 'badRequestFormat: the format of the request is invalid: multiple content sources' do - params = Parameters.new + params = DocumentParameters.new params.content = 'Por favor Senorita, says the man.?' params.content_uri = 'Por favor Senorita, says the man.?' expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(RosetteAPIError) @@ -68,7 +68,7 @@ to_return(:status => 200, :body => {'test': 'morphology/complete'}.to_json, :headers => {}) end it 'test morphology complete' do - params = Parameters.new + params = DocumentParameters.new params.content = 'The quick brown fox jumped over the lazy dog. Yes he did.' response = RosetteAPI.new('0123456789').get_morphology_complete(params) expect(response).instance_of? Hash @@ -96,7 +96,7 @@ to_return(:status => 200, :body => {'test': 'morphology/compound-components'}.to_json, :headers => {}) end it 'test morphology compound components' do - params = Parameters.new + params = DocumentParameters.new params.content = 'Rechtsschutzversicherungsgesellschaften' response = RosetteAPI.new('0123456789').get_compound_components(params) expect(response).instance_of? Hash @@ -124,7 +124,7 @@ to_return(:status => 200, :body => {'test': 'morphology/han-readings'}.to_json, :headers => {}) end it 'test morphology han readings' do - params = Parameters.new + params = DocumentParameters.new params.content = '北京大学生物系主任办公室内部会议' response = RosetteAPI.new('0123456789').get_han_readings(params) expect(response).instance_of? Hash @@ -152,7 +152,7 @@ to_return(:status => 200, :body => {'test': 'morphology/parts-of-speech'}.to_json, :headers => {}) end it 'test morphology parts of speech' do - params = Parameters.new + params = DocumentParameters.new params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" response = RosetteAPI.new('0123456789').get_parts_of_speech(params) expect(response).instance_of? Hash @@ -180,7 +180,7 @@ to_return(:status => 200, :body => {'test': 'morphology/lemmas'}.to_json, :headers => {}) end it 'test morphology lemmas' do - params = Parameters.new + params = DocumentParameters.new params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" response = RosetteAPI.new('0123456789').get_lemmas(params) expect(response).instance_of? Hash @@ -208,7 +208,7 @@ to_return(:status => 200, :body => {'test': 'entities'}.to_json, :headers => {}) end it 'test entities' do - params = Parameters.new + params = DocumentParameters.new params.content = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a' \ ' cameo in Boston this… http://dlvr.it/BnsFfS' response = RosetteAPI.new('0123456789').get_entities(params) @@ -237,7 +237,7 @@ to_return(:status => 200, :body => {'test': 'entities/linked'}.to_json, :headers => {}) end it 'test entities linked' do - params = Parameters.new + params = DocumentParameters.new params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including' \ ' Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' response = RosetteAPI.new('0123456789').get_entities_linked(params) @@ -266,7 +266,7 @@ to_return(:status => 200, :body => {'test': 'categories'}.to_json, :headers => {}) end it 'test categories' do - params = Parameters.new + params = DocumentParameters.new params.content_uri = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' response = RosetteAPI.new('0123456789').get_categories(params) expect(response).instance_of? Hash @@ -294,7 +294,7 @@ to_return(:status => 200, :body => {'test': 'relationships'}.to_json, :headers => {}) end it 'test relationships' do - params = Parameters.new + params = DocumentParameters.new params.content = 'The Ghostbusters movie was filmed in Boston.' response = RosetteAPI.new('0123456789').get_relationships(params) expect(response).instance_of? Hash @@ -322,7 +322,7 @@ to_return(:status => 200, :body => {'test': 'name-translation'}.to_json, :headers => {}) end it 'test name translation' do - params = Parameters.new + params = NameTranslationParameters.new params.name = 'معمر محمد أبو منيار القذاف'.encode('UTF-8') params.target_language = 'eng' params.target_script = 'Latn' @@ -330,8 +330,8 @@ expect(response).instance_of? Hash end - it 'badRequestFormat: needs to provide name parameter' do - params = Parameters.new + it 'badRequestFormat: needs to provide name option' do + params = NameTranslationParameters.new params.target_language = 'eng' params.target_script = 'Latn' expect { RosetteAPI.new('0123456789').name_translation(params) }.to raise_error(RosetteAPIError) @@ -359,21 +359,21 @@ to_return(:status => 200, :body => {'test': 'name-similarity'}.to_json, :headers => {}) end it 'test name similarity' do - params = Parameters.new + params = NameSimilarityParameters.new params.name1 = 'Michael Jackson' params.name2 = '迈克尔·杰克逊' response = RosetteAPI.new('0123456789').name_similarity(params) expect(response).instance_of? Hash end - it 'badRequestFormat: needs to provide name1 parameter' do - params = Parameters.new + it 'badRequestFormat: needs to provide name1 option' do + params = NameSimilarityParameters.new params.name2 = 'Michael Jackson' expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) end - it 'badRequestFormat: needs to provide name2 parameter' do - params = Parameters.new + it 'badRequestFormat: needs to provide name2 option' do + params = NameSimilarityParameters.new params.name1 = 'Michael Jackson' expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) end @@ -400,7 +400,7 @@ to_return(:status => 200, :body => {'test': 'tokens'}.to_json, :headers => {}) end it 'test tokens' do - params = Parameters.new + params = DocumentParameters.new params.content = '北京大学生物系主任办公室内部会议' response = RosetteAPI.new('0123456789').get_tokens(params) expect(response).instance_of? Hash @@ -428,7 +428,7 @@ to_return(:status => 200, :body => {'test': 'sentences'}.to_json, :headers => {}) end it 'test sentences' do - params = Parameters.new + params = DocumentParameters.new params.content = 'This land is your land. This land is my land\nFrom California to the New York island;\nFrom' \ ' the wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was' \ ' walking that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that' \ From aa0a913e07802f8525639486be9ddd6648ed5381 Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 15 Apr 2016 15:45:13 -0400 Subject: [PATCH 04/42] Fixed styling issue --- document_parameters.rb | 1 + name_similarity_parameters.rb | 2 ++ name_translation_parameters.rb | 2 ++ 3 files changed, 5 insertions(+) diff --git a/document_parameters.rb b/document_parameters.rb index 894f81b..2a3dd0d 100644 --- a/document_parameters.rb +++ b/document_parameters.rb @@ -1,4 +1,5 @@ require_relative 'rosette_api_error' + class DocumentParameters attr_accessor :content, :content_uri, :file_path, :language diff --git a/name_similarity_parameters.rb b/name_similarity_parameters.rb index f8588db..37ebbc6 100644 --- a/name_similarity_parameters.rb +++ b/name_similarity_parameters.rb @@ -1,3 +1,5 @@ +require_relative 'rosette_api_error' + class NameSimilarityParameters attr_accessor :name1, :name2 diff --git a/name_translation_parameters.rb b/name_translation_parameters.rb index 0101643..dd123eb 100644 --- a/name_translation_parameters.rb +++ b/name_translation_parameters.rb @@ -1,3 +1,5 @@ +require_relative 'rosette_api_error' + class NameTranslationParameters attr_accessor :entity_type, :name, :source_language_of_origin, :source_language_of_use, :source_script, :target_language, :target_scheme, :target_script From b83b48d821f5c9566e1bb9a2e9261902c2072de7 Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 15 Apr 2016 15:54:07 -0400 Subject: [PATCH 05/42] Deleted Parameters class --- examples/info.rb | 1 - examples/ping.rb | 1 - parameters.rb | 68 ---------------------------------------------- request_builder.rb | 1 - tests/tests.rb | 2 +- 5 files changed, 1 insertion(+), 72 deletions(-) delete mode 100644 parameters.rb diff --git a/examples/info.rb b/examples/info.rb index e40bc9f..5ada0d8 100644 --- a/examples/info.rb +++ b/examples/info.rb @@ -1,5 +1,4 @@ require '../rosette_api' -require '../parameters' api_key, url = ARGV diff --git a/examples/ping.rb b/examples/ping.rb index e2f7688..b427d82 100644 --- a/examples/ping.rb +++ b/examples/ping.rb @@ -1,5 +1,4 @@ require '../rosette_api' -require '../parameters' api_key, url = ARGV diff --git a/parameters.rb b/parameters.rb deleted file mode 100644 index b080f0b..0000000 --- a/parameters.rb +++ /dev/null @@ -1,68 +0,0 @@ -require_relative 'rosette_api_error' - -class Parameters - - attr_accessor :content, :content_uri, :language, :entity_type, :name, :source_language_of_origin, - :source_language_of_use, :source_script, :target_language, :target_scheme, :target_script, :name1, - :name2, :file_path - - def initialize - #general - @content = nil - @content_uri = nil - @file_path = nil - @language = nil - #name-translation - @entity_type = nil - @name = nil - @source_language_of_origin = nil - @source_language_of_use = nil - @source_script = nil - @target_language = nil - @target_scheme = nil - @target_script = nil - #name-similarity - @name1 = nil - @name2 = nil - end - - def to_hash - hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } - hash - end - - def validate_params - if [@content, @content_uri, @file_path].count { |attr| !attr.nil? } > 1 - raise RosetteAPIError.new(400, 'The format of the request is invalid: multiple content sources;' \ - ' must be one of an attachment, an inline "content" field, or an external "contentUri"') - elsif [@content, @content_uri, @file_path].count { |attr| attr.nil? } == 3 && [@name, @name1, @name2].count { |attr| attr.nil? } > 0 - raise RosetteAPIError.new(400, 'The format of the request is invalid: no content provided; must' \ - ' be one of an attachment, an inline "content" field, or an external "contentUri"') - else - load_params - end - end - - def validate_name_similarity_params - if @name1.nil? - raise RosetteAPIError.new(400, 'The format of the request is invalid: invalid options: name1 may not be null') - elsif @name2.nil? - raise RosetteAPIError.new(400, 'The format of the request is invalid: invalid options: name2 may not be null') - else - load_params - end - end - - def validate_name_translation_params - if @name.nil? - raise RosetteAPIError.new(400, 'The format of the request is invalid: invalid options: name: may not be null') - else - load_params - end - end - - def load_params - self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h - end -end \ No newline at end of file diff --git a/request_builder.rb b/request_builder.rb index 822aaca..1c9e2eb 100644 --- a/request_builder.rb +++ b/request_builder.rb @@ -3,7 +3,6 @@ require 'json' require 'securerandom' require_relative 'rosette_api_error' -require_relative 'parameters' class RequestBuilder attr_reader :user_key, :alternate_url, :params diff --git a/tests/tests.rb b/tests/tests.rb index caed296..788ee23 100644 --- a/tests/tests.rb +++ b/tests/tests.rb @@ -42,7 +42,7 @@ end it 'badRequestFormat: the format of the request is invalid: no content provided;' do - params = Parameters.new + params = DocumentParameters.new expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(RosetteAPIError) end end From 0bb80265e2abe57d794af2738b1d9bb50e62c150 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 18 Apr 2016 10:11:23 -0400 Subject: [PATCH 06/42] Added NameParameter class --- examples/name_similarity.rb | 7 +++++-- name_parameter.rb | 20 ++++++++++++++++++++ name_similarity_parameters.rb | 9 +++++---- tests/tests.rb | 7 +++++++ 4 files changed, 37 insertions(+), 6 deletions(-) create mode 100644 name_parameter.rb diff --git a/examples/name_similarity.rb b/examples/name_similarity.rb index 7b0de74..5d9be40 100644 --- a/examples/name_similarity.rb +++ b/examples/name_similarity.rb @@ -10,7 +10,10 @@ end params = NameSimilarityParameters.new -params.name1 = {:text => 'Michael Jackson', :language => 'eng', :entityType => 'PERSON'} -params.name2 = {:text => '迈克尔·杰克逊', :entityType => 'PERSON'} +name1 = NameParameter.new('Michael Jackson') +name1.entity_type = 'PERSON' +name1.language = 'eng' +params.name1 = name1 +params.name2 = '迈克尔·杰克逊' response = rosette_api.name_similarity(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/name_parameter.rb b/name_parameter.rb new file mode 100644 index 0000000..c942d0f --- /dev/null +++ b/name_parameter.rb @@ -0,0 +1,20 @@ +class NameParameter + attr_accessor :text, :entity_type, :language, :script + + def initialize(text) + @text = text + @entity_type = nil + @language = nil + @script = nil + end + + def load_param + self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h + end + + def to_hash + hash = {} + instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } + hash + end +end \ No newline at end of file diff --git a/name_similarity_parameters.rb b/name_similarity_parameters.rb index 37ebbc6..dffda02 100644 --- a/name_similarity_parameters.rb +++ b/name_similarity_parameters.rb @@ -1,4 +1,5 @@ require_relative 'rosette_api_error' +require_relative 'name_parameter' class NameSimilarityParameters attr_accessor :name1, :name2 @@ -12,13 +13,13 @@ def validate_params if @name1.nil? raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: invalid options: name1' \ ' not be null.') - elsif [String, Hash].count { |clazz| @name1.instance_of? clazz } == 0 - raise RosetteAPIError.new('badRequest', 'name1 option can only be an instance of a String or Hash') + elsif [String, NameParameter].count { |clazz| @name1.instance_of? clazz } == 0 + raise RosetteAPIError.new('badRequest', 'name1 option can only be an instance of a String or NameParameter') elsif @name2.nil? raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: invalid options: name2' \ ' may not be null') elsif [String, Hash].count { |clazz| @name2.instance_of? clazz } == 0 - raise RosetteAPIError.new('badRequest', 'name2 option can only be an instance of a String or Hash') + raise RosetteAPIError.new('badRequest', 'name2 option can only be an instance of a String or NameParameter') end end @@ -29,7 +30,7 @@ def load_params def to_hash hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } + instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var).instance_of?(NameParameter) ? instance_variable_get(var).load_param : instance_variable_get(var) } hash end end \ No newline at end of file diff --git a/tests/tests.rb b/tests/tests.rb index 788ee23..8874c4c 100644 --- a/tests/tests.rb +++ b/tests/tests.rb @@ -377,6 +377,13 @@ params.name1 = 'Michael Jackson' expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) end + + it 'badRequestFormat: name2 option can only be an instance of a String or NameParameter' do + params = NameSimilarityParameters.new + params.name1 = 'Michael Jackson' + params.name2 = 1234 + expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) + end end describe '.get_tokens' do From 181f0e5bb4d99b16f24bde6545657825d4d73a74 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 18 Apr 2016 11:50:19 -0400 Subject: [PATCH 07/42] Made required options for certain endpoints as required attributes. --- document_parameters.rb | 10 +++++----- examples/name_similarity.rb | 5 ++--- examples/name_translation.rb | 3 +-- name_parameter.rb | 8 ++++---- name_similarity_parameters.rb | 14 ++++---------- name_translation_parameters.rb | 28 +++++++++++----------------- tests/tests.rb | 30 +++--------------------------- 7 files changed, 30 insertions(+), 68 deletions(-) diff --git a/document_parameters.rb b/document_parameters.rb index 2a3dd0d..a265506 100644 --- a/document_parameters.rb +++ b/document_parameters.rb @@ -3,11 +3,11 @@ class DocumentParameters attr_accessor :content, :content_uri, :file_path, :language - def initialize - @content = nil - @content_uri = nil - @file_path = nil - @language = nil + def initialize(content=nil, content_uri=nil, file_path=nil, language=nil) + @content = content + @content_uri = content_uri + @file_path = file_path + @language = language end def validate_params diff --git a/examples/name_similarity.rb b/examples/name_similarity.rb index 5d9be40..4b7420c 100644 --- a/examples/name_similarity.rb +++ b/examples/name_similarity.rb @@ -9,11 +9,10 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = NameSimilarityParameters.new + name1 = NameParameter.new('Michael Jackson') name1.entity_type = 'PERSON' name1.language = 'eng' -params.name1 = name1 -params.name2 = '迈克尔·杰克逊' +params = NameSimilarityParameters.new(name1, '迈克尔·杰克逊') response = rosette_api.name_similarity(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_translation.rb b/examples/name_translation.rb index 5fb5c1f..5106dac 100644 --- a/examples/name_translation.rb +++ b/examples/name_translation.rb @@ -9,8 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = NameTranslationParameters.new -params.name = 'معمر محمد أبو منيار القذاف' +params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف') params.target_language = 'eng' params.target_script = 'Latn' response = rosette_api.name_translation(params) diff --git a/name_parameter.rb b/name_parameter.rb index c942d0f..502d0ba 100644 --- a/name_parameter.rb +++ b/name_parameter.rb @@ -1,11 +1,11 @@ class NameParameter attr_accessor :text, :entity_type, :language, :script - def initialize(text) + def initialize(text, entity_type=nil, language=nil, script=nil) @text = text - @entity_type = nil - @language = nil - @script = nil + @entity_type = entity_type + @language = language + @script = script end def load_param diff --git a/name_similarity_parameters.rb b/name_similarity_parameters.rb index dffda02..6985952 100644 --- a/name_similarity_parameters.rb +++ b/name_similarity_parameters.rb @@ -4,20 +4,14 @@ class NameSimilarityParameters attr_accessor :name1, :name2 - def initialize - @name1 = nil - @name2 = nil + def initialize(name1, name2) + @name1 = name1 + @name2 = name2 end def validate_params - if @name1.nil? - raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: invalid options: name1' \ - ' not be null.') - elsif [String, NameParameter].count { |clazz| @name1.instance_of? clazz } == 0 + if [String, NameParameter].count { |clazz| @name1.instance_of? clazz } == 0 raise RosetteAPIError.new('badRequest', 'name1 option can only be an instance of a String or NameParameter') - elsif @name2.nil? - raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: invalid options: name2' \ - ' may not be null') elsif [String, Hash].count { |clazz| @name2.instance_of? clazz } == 0 raise RosetteAPIError.new('badRequest', 'name2 option can only be an instance of a String or NameParameter') end diff --git a/name_translation_parameters.rb b/name_translation_parameters.rb index dd123eb..6790457 100644 --- a/name_translation_parameters.rb +++ b/name_translation_parameters.rb @@ -1,28 +1,22 @@ require_relative 'rosette_api_error' class NameTranslationParameters - attr_accessor :entity_type, :name, :source_language_of_origin, :source_language_of_use, :source_script, + attr_accessor :name, :entity_type, :source_language_of_origin, :source_language_of_use, :source_script, :target_language, :target_scheme, :target_script - def initialize - @entity_type = nil - @name = nil - @source_language_of_origin = nil - @source_language_of_use = nil - @source_script = nil - @target_language = nil - @target_scheme = nil - @target_script = nil - end - - def validate_params - if @name.nil? - raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: invalid options: name: may not be null') - end + def initialize(name, entity_type=nil, source_language_of_origin=nil, source_language_of_use=nil, source_script=nil, + target_language=nil, target_scheme=nil, target_script=nil) + @name = name + @entity_type = entity_type + @source_language_of_origin = source_language_of_origin + @source_language_of_use = source_language_of_use + @source_script = source_script + @target_language = target_language + @target_scheme = target_scheme + @target_script = target_script end def load_params - validate_params self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h end diff --git a/tests/tests.rb b/tests/tests.rb index 8874c4c..78ede8a 100644 --- a/tests/tests.rb +++ b/tests/tests.rb @@ -322,20 +322,12 @@ to_return(:status => 200, :body => {'test': 'name-translation'}.to_json, :headers => {}) end it 'test name translation' do - params = NameTranslationParameters.new - params.name = 'معمر محمد أبو منيار القذاف'.encode('UTF-8') + params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8')) params.target_language = 'eng' params.target_script = 'Latn' response = RosetteAPI.new('0123456789').name_translation(params) expect(response).instance_of? Hash end - - it 'badRequestFormat: needs to provide name option' do - params = NameTranslationParameters.new - params.target_language = 'eng' - params.target_script = 'Latn' - expect { RosetteAPI.new('0123456789').name_translation(params) }.to raise_error(RosetteAPIError) - end end describe '.name_similarity' do @@ -359,29 +351,13 @@ to_return(:status => 200, :body => {'test': 'name-similarity'}.to_json, :headers => {}) end it 'test name similarity' do - params = NameSimilarityParameters.new - params.name1 = 'Michael Jackson' - params.name2 = '迈克尔·杰克逊' + params = NameSimilarityParameters.new('Michael Jackson', '迈克尔·杰克逊') response = RosetteAPI.new('0123456789').name_similarity(params) expect(response).instance_of? Hash end - it 'badRequestFormat: needs to provide name1 option' do - params = NameSimilarityParameters.new - params.name2 = 'Michael Jackson' - expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) - end - - it 'badRequestFormat: needs to provide name2 option' do - params = NameSimilarityParameters.new - params.name1 = 'Michael Jackson' - expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) - end - it 'badRequestFormat: name2 option can only be an instance of a String or NameParameter' do - params = NameSimilarityParameters.new - params.name1 = 'Michael Jackson' - params.name2 = 1234 + params = NameSimilarityParameters.new('Michael Jackson', 123) expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) end end From a9e07031d358daa74097e2f17b3bf705f5d289ec Mon Sep 17 00:00:00 2001 From: Chris Park Date: Tue, 19 Apr 2016 09:30:49 -0400 Subject: [PATCH 08/42] Updated README --- README.md | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 20e4fc1..50021d5 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,34 @@ --- -# Ruby Examples for Rosette API +# Ruby Binding for Rosette API --- ### Summary -This repository provides Ruby script examples for each of the supported Rosette API endpoints. +This repository provides a Ruby binding and examples for each of the supported Rosette API endpoints. ### Basic Usage Install Ruby if you haven't already. Instructions can be found [here](https://www.ruby-lang.org/en/documentation/installation/). Once Ruby is installed simply run the example as: `ruby examplefile.rb your_api_key` to see the results. + +### Docker + +A Dockerfile may be built (examples/docker) to run the examples and unit tests + +1. `sudo docker build --rm -t ruby-docker .` +1. `cd ruby_root_direcory` +1. `sudo docker run --rm -e API_KEY=valid_api_key -v `pwd`:/source ruby-docker` + +### Testing + +Unit tests are based on RSpec. + +1. Launch the docker image interactively, `sudo docker run --rm -it -e API_KEY=valid_api_key -v `pwd`:/source ruby-docker /bin/bash` +1. `cd tests` +1. `rspec tests.rb` + +### Gem Package + +Coming soon + + From 28c6ca45328be93967d11c5367bc376c6ee270e1 Mon Sep 17 00:00:00 2001 From: Christopher Park Date: Tue, 19 Apr 2016 10:01:44 -0400 Subject: [PATCH 09/42] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 50021d5..e0b407e 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ --- -# Ruby Binding for Rosette API +# Ruby Binding for Rosette API (Beta) --- ### Summary From 7db2b63d222aac48e13e65ca8f4908c9cd7d8f6e Mon Sep 17 00:00:00 2001 From: Jeremy Day Date: Sun, 24 Apr 2016 11:35:37 -0500 Subject: [PATCH 10/42] I reworked the code using a few more common ruby idioms. --- .gitignore | 1 + .ruby-version | 1 + Gemfile | 15 ++ Gemfile.lock | 58 ++++++++ bad_request_error.rb | 7 + bad_request_format_error.rb | 7 + document_parameters.rb | 47 ++++--- name_parameter.rb | 33 +++-- name_similarity_parameters.rb | 25 ++-- name_translation_parameters.rb | 55 +++++--- request_builder.rb | 53 +++---- rosette_api.rb | 208 ++++++++++++++------------- tests/{tests.rb => tests_spec.rb} | 226 +++++++++++++++--------------- 13 files changed, 447 insertions(+), 289 deletions(-) create mode 100644 .ruby-version create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 bad_request_error.rb create mode 100644 bad_request_format_error.rb rename tests/{tests.rb => tests_spec.rb} (68%) diff --git a/.gitignore b/.gitignore index a8b1cda..52f966b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +*~ *.gem *.rbc /.config diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..f962b8e --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-2.3.0@rosette-api diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..54f17bb --- /dev/null +++ b/Gemfile @@ -0,0 +1,15 @@ +source "https://rubygems.org" + +gem 'rubygems-update', '2.6.3' +gem 'rubysl-securerandom', '2.0.0' +gem 'safe_yaml', '1.0.4' +gem 'simplecov', '0.11.2' +gem 'simplecov-html', '0.10.0' + +gem 'rspec', '3.4.0', group: [:test] +gem 'rspec-core', '3.4.4', group: [:test] +gem 'rspec-expectations', '3.4.0', group: [:test] +gem 'rspec-mocks', '3.4.1', group: [:test] +gem 'rspec-support', '3.4.1', group: [:test] +gem 'test-unit', '3.1.5', group: [:test] +gem 'webmock', '1.24.5', group: [:test] diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..7282e9b --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,58 @@ +GEM + remote: https://rubygems.org/ + specs: + addressable (2.4.0) + crack (0.4.3) + safe_yaml (~> 1.0.0) + diff-lcs (1.2.5) + docile (1.1.5) + hashdiff (0.3.0) + json (1.8.3) + power_assert (0.2.7) + rspec (3.4.0) + rspec-core (~> 3.4.0) + rspec-expectations (~> 3.4.0) + rspec-mocks (~> 3.4.0) + rspec-core (3.4.4) + rspec-support (~> 3.4.0) + rspec-expectations (3.4.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.4.0) + rspec-mocks (3.4.1) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.4.0) + rspec-support (3.4.1) + rubygems-update (2.6.3) + rubysl-securerandom (2.0.0) + safe_yaml (1.0.4) + simplecov (0.11.2) + docile (~> 1.1.0) + json (~> 1.8) + simplecov-html (~> 0.10.0) + simplecov-html (0.10.0) + test-unit (3.1.5) + power_assert + webmock (1.24.5) + addressable (>= 2.3.6) + crack (>= 0.3.2) + hashdiff + +PLATFORMS + ruby + +DEPENDENCIES + rspec (= 3.4.0) + rspec-core (= 3.4.4) + rspec-expectations (= 3.4.0) + rspec-mocks (= 3.4.1) + rspec-support (= 3.4.1) + rubygems-update (= 2.6.3) + rubysl-securerandom (= 2.0.0) + safe_yaml (= 1.0.4) + simplecov (= 0.11.2) + simplecov-html (= 0.10.0) + test-unit (= 3.1.5) + webmock (= 1.24.5) + +BUNDLED WITH + 1.11.2 diff --git a/bad_request_error.rb b/bad_request_error.rb new file mode 100644 index 0000000..3d585d5 --- /dev/null +++ b/bad_request_error.rb @@ -0,0 +1,7 @@ +require_relative 'rosette_api_error' + +class BadRequestError < RosetteAPIError + def initialize(message) + super 'badRequest', message + end +end diff --git a/bad_request_format_error.rb b/bad_request_format_error.rb new file mode 100644 index 0000000..3627d25 --- /dev/null +++ b/bad_request_format_error.rb @@ -0,0 +1,7 @@ +require_relative 'rosette_api_error' + +class BadRequestFormatError < RosetteAPIError + def initialize(message) + super 'badRequestFormat', message + end +end diff --git a/document_parameters.rb b/document_parameters.rb index a265506..df065b5 100644 --- a/document_parameters.rb +++ b/document_parameters.rb @@ -1,33 +1,44 @@ -require_relative 'rosette_api_error' +require_relative 'bad_request_format_error' class DocumentParameters attr_accessor :content, :content_uri, :file_path, :language - def initialize(content=nil, content_uri=nil, file_path=nil, language=nil) - @content = content - @content_uri = content_uri - @file_path = file_path - @language = language + def initialize(options = {}) + options = { + 'content' => nil, + 'content_uri' => nil, + 'file_path' => nil, + 'language' => nil + }.update options + @content = options['content'] + @content_uri = options['content_uri'] + @file_path = options['file_path'] + @language = options['language'] end def validate_params - if [@content, @content_uri, @file_path].count { |attr| !attr.nil? } > 1 - raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: multiple content sources;' \ - ' must be one of an attachment, an inline "content" field, or an external "contentUri"') - elsif [@content, @content_uri, @file_path].count { |attr| attr.nil? } == 3 - raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: no content provided; must' \ - ' be one of an attachment, an inline "content" field, or an external "contentUri"') + if [@content, @content_uri, @file_path].compact.length > 1 + raise BadRequestFormatError.new 'The format of the request is invalid: multiple content sources;' \ + ' must be one of an attachment, an inline "content" field, or an external "contentUri"' + elsif [@content, @content_uri, @file_path].all?(&:nil?) + raise BadRequestFormatError.new 'The format of the request is invalid: no content provided; must' \ + ' be one of an attachment, an inline "content" field, or an external "contentUri"' end end def load_params - validate_params - self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h + self.validate_params + self.to_hash.select { |key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h end def to_hash - hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } - hash + { + 'content' => @content, + 'content_uri' => @content_uri, + 'file_path' => @file_path, + 'language' => @language + } end -end \ No newline at end of file +end diff --git a/name_parameter.rb b/name_parameter.rb index 502d0ba..bbc8534 100644 --- a/name_parameter.rb +++ b/name_parameter.rb @@ -1,20 +1,33 @@ class NameParameter - attr_accessor :text, :entity_type, :language, :script + attr_accessor :entity_type, + :language, + :script, + :text - def initialize(text, entity_type=nil, language=nil, script=nil) + def initialize(text, option = {}) + options = { + 'entity_type' => nil, + 'language' => nil, + 'script' => nil + }.update options @text = text - @entity_type = entity_type - @language = language - @script = script + @entity_type = options['entity_type'] + @language = options['language'] + @script = options['script'] end def load_param - self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h + self.to_hash.select { |key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h end def to_hash - hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } - hash + { + 'entity_type' => @entity_type, + 'language' => @language, + 'script' => @script, + 'text' => @text + } end -end \ No newline at end of file +end diff --git a/name_similarity_parameters.rb b/name_similarity_parameters.rb index 6985952..57ea177 100644 --- a/name_similarity_parameters.rb +++ b/name_similarity_parameters.rb @@ -1,4 +1,4 @@ -require_relative 'rosette_api_error' +require_relative 'bad_request_error' require_relative 'name_parameter' class NameSimilarityParameters @@ -10,21 +10,24 @@ def initialize(name1, name2) end def validate_params - if [String, NameParameter].count { |clazz| @name1.instance_of? clazz } == 0 - raise RosetteAPIError.new('badRequest', 'name1 option can only be an instance of a String or NameParameter') - elsif [String, Hash].count { |clazz| @name2.instance_of? clazz } == 0 - raise RosetteAPIError.new('badRequest', 'name2 option can only be an instance of a String or NameParameter') + if [String, NameParameter].none? { |clazz| @name1.is_a? clazz } + raise BadRequestError.new('name1 option can only be an instance of a String or NameParameter') + elsif [String, NameParameter].none? { |clazz| @name2.is_a? clazz } + raise BadRequestError.new('name2 option can only be an instance of a String or NameParameter') end end def load_params - validate_params - self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h + self.validate_params + self.to_hash.select { |key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h end def to_hash - hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var).instance_of?(NameParameter) ? instance_variable_get(var).load_param : instance_variable_get(var) } - hash + { + 'name1' => @name1.is_a?(NameParameter) ? @name1.load_param : @name1, + 'name2' => @name2.is_a?(NameParameter) ? @name2.load_param : @name2 + } end -end \ No newline at end of file +end diff --git a/name_translation_parameters.rb b/name_translation_parameters.rb index 6790457..456e1e7 100644 --- a/name_translation_parameters.rb +++ b/name_translation_parameters.rb @@ -1,28 +1,51 @@ require_relative 'rosette_api_error' class NameTranslationParameters - attr_accessor :name, :entity_type, :source_language_of_origin, :source_language_of_use, :source_script, - :target_language, :target_scheme, :target_script + attr_accessor :entity_type, + :name, + :source_language_of_origin, + :source_language_of_use, + :source_script, + :target_language, + :target_scheme, + :target_script - def initialize(name, entity_type=nil, source_language_of_origin=nil, source_language_of_use=nil, source_script=nil, - target_language=nil, target_scheme=nil, target_script=nil) + def initialize(name, options = {}) + options = { + 'entity_type' => nil, + 'source_language_of_origin' => nil, + 'source_language_of_use' => nil, + 'source_script' => nil, + 'target_language' => nil, + 'target_scheme' => nil, + 'target_script' => nil + }.update options @name = name - @entity_type = entity_type - @source_language_of_origin = source_language_of_origin - @source_language_of_use = source_language_of_use - @source_script = source_script - @target_language = target_language - @target_scheme = target_scheme - @target_script = target_script + @entity_type = options['entity_type'] + @source_language_of_origin = options['source_language_of_origin'] + @source_language_of_use = options['source_language_of_use'] + @source_script = options['source_script'] + @target_language = options['target_language'] + @target_scheme = options['target_scheme'] + @target_script = options['target_script'] end def load_params - self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h + self.to_hash.select { |key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h end def to_hash - hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } - hash + { + 'entity_type' => @entity_type, + 'name' => @name, + 'source_language_of_origin' => @source_language_of_origin, + 'source_language_of_use' => @source_language_of_use, + 'source_script' => @source_script, + 'target_language' => @target_language, + 'target_scheme' => @target_scheme, + 'target_script' => @target_script + } end -end \ No newline at end of file +end diff --git a/request_builder.rb b/request_builder.rb index 1c9e2eb..49370d9 100644 --- a/request_builder.rb +++ b/request_builder.rb @@ -5,20 +5,20 @@ require_relative 'rosette_api_error' class RequestBuilder - attr_reader :user_key, :alternate_url, :params + attr_reader :alternate_url, :params, :user_key - def initialize(user_key, alternate_url, params={}) + def initialize(user_key, alternate_url, params = {}) @user_key = user_key @alternate_url = alternate_url @params = params end def prepare_plain_request(params) - uri = URI.parse(@alternate_url) - http = Net::HTTP.new(uri.host, uri.port) - http.use_ssl = true if uri.scheme == 'https' + uri = URI.parse @alternate_url + http = Net::HTTP.new uri.host, uri.port + http.use_ssl = uri.scheme == 'https' - request = Net::HTTP::Post.new(uri.request_uri) + request = Net::HTTP::Post.new uri.request_uri request['X-RosetteAPI-Key'] = @user_key request['Content-Type'] = 'application/json' request['Accept'] = 'application/json' @@ -29,7 +29,7 @@ def prepare_plain_request(params) def prepare_multipart_request(params) begin - file = File.open(params['filePath'], 'r') + file = File.open params['filePath'], 'r' text = file.read rescue => err raise err @@ -53,26 +53,26 @@ def prepare_multipart_request(params) post_body << "\r\n\r\n--#{boundary}--\r\n" # Create the HTTP objects - uri = URI.parse(@alternate_url) - http = Net::HTTP.new(uri.host, uri.port) - http.use_ssl = true if uri.scheme == 'https' - request = Net::HTTP::Post.new(uri.request_uri) - request.add_field('Content-Type', "multipart/form-data; boundary=#{boundary}") - request.add_field('X-RosetteAPI-Key', @user_key) + uri = URI.parse @alternate_url + http = Net::HTTP.new uri.host, uri.port + http.use_ssl = uri.scheme == 'https' + request = Net::HTTP::Post.new uri.request_uri + request.add_field 'Content-Type', "multipart/form-data; boundary=#{boundary}" + request.add_field 'X-RosetteAPI-Key', @user_key request.body = post_body.join [http, request] end def send_get_request - uri = URI.parse(@alternate_url) - http = Net::HTTP.new(uri.host, uri.port) - http.use_ssl = true if uri.scheme == 'https' + uri = URI.parse @alternate_url + http = Net::HTTP.new uri.host, uri.port + http.use_ssl = uri.scheme == 'https' - request = Net::HTTP::Get.new(uri.request_uri) + request = Net::HTTP::Get.new uri.request_uri request['X-RosetteAPI-Key'] = @user_key - get_response(http, request) + self.get_response http, request end def send_post_request @@ -83,16 +83,17 @@ def send_post_request end if !params['filePath'].nil? - http, request = prepare_multipart_request(params) + http, request = self.prepare_multipart_request params else - http, request = prepare_plain_request(params) + http, request = self.prepare_plain_request params end - get_response(http, request) + self.get_response http, request end def get_response(http, request) - response = http.request(request) + response = http.request request + if response.code != '200' message = if JSON.parse(response.body)['message'].nil? @@ -100,12 +101,14 @@ def get_response(http, request) else JSON.parse(response.body)['message'] end - raise RosetteAPIError.new(response.code, message) + + raise RosetteAPIError.new response.code, message else response_headers = {} response.header.each_header { |key, value| response_headers[key] = value } - response_headers = {:responseHeaders => response_headers} + response_headers = { responseHeaders: response_headers } + JSON.parse(response.body).merge(response_headers) end end -end \ No newline at end of file +end diff --git a/rosette_api.rb b/rosette_api.rb index 4aae6f1..0ddd147 100644 --- a/rosette_api.rb +++ b/rosette_api.rb @@ -3,6 +3,8 @@ require_relative 'name_translation_parameters' require_relative 'name_similarity_parameters' require_relative 'rosette_api_error' +require_relative 'bad_request_error' +require_relative 'bad_request_format_error' class RosetteAPI BINDING_VERSION = '1.0.2' @@ -23,164 +25,176 @@ class RosetteAPI attr_accessor :user_key, :alternate_url - def initialize(user_key, alternate_url='https://api.rosette.com/rest/v1') + def initialize(user_key, alternate_url = 'https://api.rosette.com/rest/v1') @user_key = user_key @alternate_url = alternate_url + if @alternate_url.to_s.end_with?('/') @alternate_url = alternate_url.to_s.slice(0..-2) end - check_version_compatibility + + self.check_version_compatibility end def check_version_compatibility - response = RequestBuilder.new(@user_key, @alternate_url + VERSION_CHECK).send_post_request + response = RequestBuilder.new(@user_key, @alternate_url + VERSION_CHECK) + .send_post_request + unless response['versionChecked'] puts JSON.pretty_generate(response) + exit end end def get_language(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + LANGUAGE_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + LANGUAGE_ENDPOINT, params) + .send_post_request end def get_morphology_complete(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/complete', params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/complete', params) + .send_post_request end def get_compound_components(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url +MORPHOLOGY_ENDPOINT + '/compound-components', params) - .send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url +MORPHOLOGY_ENDPOINT + '/compound-components', params) + .send_post_request end def get_han_readings(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/han-readings', params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/han-readings', params) + .send_post_request end def get_lemmas(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/lemmas', params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/lemmas', params) + .send_post_request end def get_parts_of_speech(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/parts-of-speech', params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/parts-of-speech', params) + .send_post_request end def get_entities(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + ENTITIES_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + ENTITIES_ENDPOINT, params) + .send_post_request end def get_entities_linked(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + ENTITIES_LINKED_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + ENTITIES_LINKED_ENDPOINT, params) + .send_post_request end def get_categories(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + CATEGORIES_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + CATEGORIES_ENDPOINT, params) + .send_post_request end def get_relationships(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + RELATIONSHIPS_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + RELATIONSHIPS_ENDPOINT, params) + .send_post_request end def get_sentiment(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + SENTIMENT_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + SENTIMENT_ENDPOINT, params) + .send_post_request end def name_translation(params) - if params.instance_of? NameTranslationParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + NAME_TRANSLATION_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a NameTranslationParameters type as an argument') - end + check_params params, 'Expects a NameTranslationParameters type as an argument', NameTranslationParameters + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + NAME_TRANSLATION_ENDPOINT, params) + .send_post_request end def name_similarity(params) - if params.instance_of? NameSimilarityParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + NAME_SIMILARITY_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a NameSimilarityParameters type as an argument') - end + check_params params, 'Expects a NameSimilarityParameters type as an argument', NameSimilarityParameters + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + NAME_SIMILARITY_ENDPOINT, params) + .send_post_request end def get_tokens(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + TOKENS_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + TOKENS_ENDPOINT, params) + .send_post_request end def get_sentences(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + SENTENCES_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + SENTENCES_ENDPOINT, params) + .send_post_request end def info - RequestBuilder.new(@user_key, @alternate_url + INFO).send_get_request + RequestBuilder.new(@user_key, @alternate_url + INFO) + .send_get_request end def ping - RequestBuilder.new(@user_key, @alternate_url + PING).send_get_request + RequestBuilder.new(@user_key, @alternate_url + PING) + .send_get_request end -end \ No newline at end of file + + private + + def check_params(params, message = 'Expects a DocumentParameters type as an argument', type = DocumentParameters) + raise BadRequest.new message unless params.is_a? type + end +end diff --git a/tests/tests.rb b/tests/tests_spec.rb similarity index 68% rename from tests/tests.rb rename to tests/tests_spec.rb index 78ede8a..edd7890 100644 --- a/tests/tests.rb +++ b/tests/tests_spec.rb @@ -3,29 +3,29 @@ require 'rspec' require 'webmock/rspec' require 'json' -WebMock.disable_net_connect!(:allow_localhost => true) +WebMock.disable_net_connect!(allow_localhost: true) describe RosetteAPI do describe '.get_language' do - request_file = File.open('../mock-data/request/language.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/language.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/language'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'language'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'language'}.to_json, headers: {}) end it 'test language' do params = DocumentParameters.new @@ -38,34 +38,36 @@ params = DocumentParameters.new params.content = 'Por favor Senorita, says the man.?' params.content_uri = 'Por favor Senorita, says the man.?' - expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(RosetteAPIError) + expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(BadRequestFormatError) end it 'badRequestFormat: the format of the request is invalid: no content provided;' do params = DocumentParameters.new - expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(RosetteAPIError) + expect { RosetteAPI.new('0123456789') + .get_language(params) } + .to raise_error(BadRequestFormatError) end end describe '.get_morphology_complete' do - request_file = File.open('../mock-data/request/morphology_complete.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_complete.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/complete'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/complete'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/complete'}.to_json, headers: {}) end it 'test morphology complete' do params = DocumentParameters.new @@ -76,24 +78,24 @@ end describe '.get_compound_components' do - request_file = File.open('../mock-data/request/morphology_compound_components.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_compound_components.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/compound-components'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/compound-components'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/compound-components'}.to_json, headers: {}) end it 'test morphology compound components' do params = DocumentParameters.new @@ -104,24 +106,24 @@ end describe '.get_han_readings' do - request_file = File.open('../mock-data/request/morphology_han_readings.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_han_readings.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/han-readings'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/han-readings'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/han-readings'}.to_json, headers: {}) end it 'test morphology han readings' do params = DocumentParameters.new @@ -132,24 +134,24 @@ end describe '.get_parts_of_speech' do - request_file = File.open('../mock-data/request/morphology_parts_of_speech.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_parts_of_speech.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/parts-of-speech'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/parts-of-speech'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/parts-of-speech'}.to_json, headers: {}) end it 'test morphology parts of speech' do params = DocumentParameters.new @@ -160,24 +162,24 @@ end describe '.get_lemmas' do - request_file = File.open('../mock-data/request/morphology_lemmas.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_lemmas.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/lemmas'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/lemmas'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/lemmas'}.to_json, headers: {}) end it 'test morphology lemmas' do params = DocumentParameters.new @@ -188,24 +190,24 @@ end describe '.get_entities' do - request_file = File.open('../mock-data/request/entities.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/entities'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'entities'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'entities'}.to_json, headers: {}) end it 'test entities' do params = DocumentParameters.new @@ -217,24 +219,24 @@ end describe '.get_entities_linked' do - request_file = File.open('../mock-data/request/entities_linked.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities_linked.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/entities/linked'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'entities/linked'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'entities/linked'}.to_json, headers: {}) end it 'test entities linked' do params = DocumentParameters.new @@ -246,24 +248,24 @@ end describe '.get_categories' do - request_file = File.open('../mock-data/request/categories.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/categories.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/categories'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'categories'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'categories'}.to_json, headers: {}) end it 'test categories' do params = DocumentParameters.new @@ -274,24 +276,24 @@ end describe '.get_relationships' do - request_file = File.open('../mock-data/request/relationships.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/relationships.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/relationships'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'relationships'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'relationships'}.to_json, headers: {}) end it 'test relationships' do params = DocumentParameters.new @@ -302,24 +304,24 @@ end describe '.name_translation' do - request_file = File.open('../mock-data/request/name_translation.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_translation.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/name-translation'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'name-translation'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'name-translation'}.to_json, headers: {}) end it 'test name translation' do params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8')) @@ -331,24 +333,24 @@ end describe '.name_similarity' do - request_file = File.open('../mock-data/request/name_similarity.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_similarity.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/name-similarity'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'name-similarity'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'name-similarity'}.to_json, headers: {}) end it 'test name similarity' do params = NameSimilarityParameters.new('Michael Jackson', '迈克尔·杰克逊') @@ -358,29 +360,29 @@ it 'badRequestFormat: name2 option can only be an instance of a String or NameParameter' do params = NameSimilarityParameters.new('Michael Jackson', 123) - expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) + expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(BadRequestError) end end describe '.get_tokens' do - request_file = File.open('../mock-data/request/tokens.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/tokens.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/tokens'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'tokens'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'tokens'}.to_json, headers: {}) end it 'test tokens' do params = DocumentParameters.new @@ -391,24 +393,24 @@ end describe '.get_sentences' do - request_file = File.open('../mock-data/request/sentences.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/sentences.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/sentences'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'sentences'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'sentences'}.to_json, headers: {}) end it 'test sentences' do params = DocumentParameters.new @@ -424,19 +426,19 @@ describe '.info' do before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:get, 'https://api.rosette.com/rest/v1/info'). - with(:headers => {'Accept' => '*/*', + with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'info'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'info'}.to_json, headers: {}) end it 'test info' do response = RosetteAPI.new('0123456789').info @@ -447,19 +449,19 @@ describe '.ping' do before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:get, 'https://api.rosette.com/rest/v1/ping'). - with(:headers => {'Accept' => '*/*', + with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'ping'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'ping'}.to_json, headers: {}) end it 'test ping' do response = RosetteAPI.new('0123456789').ping From 087d80e16831198bb9ff548a1ca6bfe693e2a802 Mon Sep 17 00:00:00 2001 From: fiona Date: Wed, 27 Apr 2016 16:33:03 -0400 Subject: [PATCH 11/42] Added documentation to classes, methods. --- examples/categories.rb | 7 +- examples/docker/Dockerfile | 7 +- examples/docker/run_ruby.sh | 21 ++++- examples/entities.rb | 8 +- examples/entities_linked.rb | 8 +- examples/info.rb | 2 +- examples/language.rb | 7 +- examples/morphology_complete.rb | 7 +- examples/morphology_compound_components.rb | 7 +- examples/morphology_han_readings.rb | 7 +- examples/morphology_lemmas.rb | 7 +- examples/morphology_parts_of_speech.rb | 7 +- examples/name_similarity.rb | 8 +- examples/name_translation.rb | 8 +- examples/ping.rb | 2 +- examples/relationships.rb | 7 +- examples/sentences.rb | 4 +- examples/sentiment.rb | 9 +- examples/tokens.rb | 7 +- name_parameter.rb | 33 ------- name_translation_parameters.rb | 51 ----------- .../bad_request_error.rb | 1 + .../bad_request_format_error.rb | 1 + .../document_parameters.rb | 34 ++++--- rosette_api/name_parameter.rb | 40 +++++++++ .../name_similarity_parameters.rb | 14 ++- rosette_api/name_translation_parameters.rb | 59 ++++++++++++ .../request_builder.rb | 32 ++++++- rosette_api.rb => rosette_api/rosette_api.rb | 89 +++++++++++++++++++ .../rosette_api_error.rb | 2 + tests/tests_spec.rb | 2 +- 31 files changed, 329 insertions(+), 169 deletions(-) delete mode 100644 name_parameter.rb delete mode 100644 name_translation_parameters.rb rename bad_request_error.rb => rosette_api/bad_request_error.rb (72%) rename bad_request_format_error.rb => rosette_api/bad_request_format_error.rb (70%) rename document_parameters.rb => rosette_api/document_parameters.rb (59%) create mode 100644 rosette_api/name_parameter.rb rename name_similarity_parameters.rb => rosette_api/name_similarity_parameters.rb (63%) create mode 100644 rosette_api/name_translation_parameters.rb rename request_builder.rb => rosette_api/request_builder.rb (74%) rename rosette_api.rb => rosette_api/rosette_api.rb (59%) rename rosette_api_error.rb => rosette_api/rosette_api_error.rb (67%) diff --git a/examples/categories.rb b/examples/categories.rb index 8083b60..caa6131 100644 --- a/examples/categories.rb +++ b/examples/categories.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require_relative '../rosette_api/rosette_api' +require_relative '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,7 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content_uri = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' +params = DocumentParameters.new(content_uri: 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/') response = rosette_api.get_categories(params) puts JSON.pretty_generate(response) diff --git a/examples/docker/Dockerfile b/examples/docker/Dockerfile index eed3058..2ab892b 100644 --- a/examples/docker/Dockerfile +++ b/examples/docker/Dockerfile @@ -9,10 +9,11 @@ RUN apt-get -y update && apt-get install -y \ RUN gem install rubysl-securerandom \ rspec \ webmock \ - simplecov + simplecov \ + tomdoc -RUN mkdir /ruby -WORKDIR /ruby +RUN mkdir /ruby-dev +WORKDIR /ruby-dev COPY run_ruby.sh run_ruby.sh RUN chmod 0755 run_ruby.sh diff --git a/examples/docker/run_ruby.sh b/examples/docker/run_ruby.sh index efe2d2d..96aef60 100644 --- a/examples/docker/run_ruby.sh +++ b/examples/docker/run_ruby.sh @@ -79,7 +79,7 @@ cp -r -n /source/. . if [ ! -z ${API_KEY} ]; then checkAPI cd tests - rspec tests.rb + rspec tests_spec.rb cd ../examples if [ ! -z ${FILENAME} ]; then runExample ${FILENAME} @@ -92,4 +92,23 @@ else HELP fi +#Generate gh-pages and push them to git account (if git username is provided) +if [ ! -z ${GIT_USERNAME} ] && [ ! -z ${VERSION} ]; then + #clone ruby git repo + cd / + git clone git@github.com:${GIT_USERNAME}/ruby.git + cd ruby + git checkout origin/gh-pages -b gh-pages + git branch -d develop + #generate gh-pages and set ouput dir to git repo (gh-pages branch) + cd /ruby-dev + for file in *.rb; do + tomdoc -f html ${file} + done + cd /ruby + git add . + git commit -a -m "publish ruby apidocs ${VERSION}" + git push +fi + exit ${retcode} diff --git a/examples/entities.rb b/examples/entities.rb index f36dd61..e6f2087 100644 --- a/examples/entities.rb +++ b/examples/entities.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,8 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo ' \ - 'in Boston this… http://dlvr.it/BnsFfS' +params = DocumentParameters.new(content: 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS') response = rosette_api.get_entities(params) puts JSON.pretty_generate(response) diff --git a/examples/entities_linked.rb b/examples/entities_linked.rb index 73668a7..501473e 100644 --- a/examples/entities_linked.rb +++ b/examples/entities_linked.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,8 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including ' \ - 'Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' +params = DocumentParameters.new(content: 'Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.') response = rosette_api.get_entities_linked(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/info.rb b/examples/info.rb index 5ada0d8..4762f39 100644 --- a/examples/info.rb +++ b/examples/info.rb @@ -1,4 +1,4 @@ -require '../rosette_api' +require '../rosette_api/rosette_api' api_key, url = ARGV diff --git a/examples/language.rb b/examples/language.rb index dc83754..31e1505 100644 --- a/examples/language.rb +++ b/examples/language.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,7 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'Por favor Señorita, says the man.?' +params = DocumentParameters.new(content: 'Por favor Señorita, says the man.?') response = rosette_api.get_language(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_complete.rb b/examples/morphology_complete.rb index ec50486..c192a74 100644 --- a/examples/morphology_complete.rb +++ b/examples/morphology_complete.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,7 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'The quick brown fox jumped over the lazy dog. Yes he did.' +params = DocumentParameters.new(content: 'The quick brown fox jumped over the lazy dog. Yes he did.') response = rosette_api.get_morphology_complete(params) puts JSON.pretty_generate(response) diff --git a/examples/morphology_compound_components.rb b/examples/morphology_compound_components.rb index 698fb4e..05f7af1 100644 --- a/examples/morphology_compound_components.rb +++ b/examples/morphology_compound_components.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,7 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'Rechtsschutzversicherungsgesellschaften' +params = DocumentParameters.new(content: 'Rechtsschutzversicherungsgesellschaften') response = rosette_api.get_compound_components(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_han_readings.rb b/examples/morphology_han_readings.rb index 57d1f7d..412b002 100644 --- a/examples/morphology_han_readings.rb +++ b/examples/morphology_han_readings.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,7 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = '北京大学生物系主任办公室内部会议' +params = DocumentParameters.new(content: '北京大学生物系主任办公室内部会议') response = rosette_api.get_han_readings(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_lemmas.rb b/examples/morphology_lemmas.rb index 5fdb4df..d45c1ea 100644 --- a/examples/morphology_lemmas.rb +++ b/examples/morphology_lemmas.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,7 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" +params = DocumentParameters.new(content: "The fact is that the geese just went back to get a rest and I'm not banking on their return soon") response = rosette_api.get_lemmas(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_parts_of_speech.rb b/examples/morphology_parts_of_speech.rb index ffc2c09..4653089 100644 --- a/examples/morphology_parts_of_speech.rb +++ b/examples/morphology_parts_of_speech.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,7 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" +params = DocumentParameters.new(content: "The fact is that the geese just went back to get a rest and I'm not banking on their return soon") response = rosette_api.get_parts_of_speech(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_similarity.rb b/examples/name_similarity.rb index 4b7420c..b9f267a 100644 --- a/examples/name_similarity.rb +++ b/examples/name_similarity.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../name_similarity_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/name_similarity_parameters' api_key, url = ARGV @@ -10,9 +10,7 @@ end -name1 = NameParameter.new('Michael Jackson') -name1.entity_type = 'PERSON' -name1.language = 'eng' +name1 = NameParameter.new('Michael Jackson', entity_type: 'PERSON', language:'eng') params = NameSimilarityParameters.new(name1, '迈克尔·杰克逊') response = rosette_api.name_similarity(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_translation.rb b/examples/name_translation.rb index 5106dac..b1c653c 100644 --- a/examples/name_translation.rb +++ b/examples/name_translation.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../name_translation_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/name_translation_parameters' api_key, url = ARGV @@ -9,8 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف') -params.target_language = 'eng' -params.target_script = 'Latn' +params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف', target_language: 'eng', target_script: 'Latn') response = rosette_api.name_translation(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/ping.rb b/examples/ping.rb index b427d82..1ac1862 100644 --- a/examples/ping.rb +++ b/examples/ping.rb @@ -1,4 +1,4 @@ -require '../rosette_api' +require '../rosette_api/rosette_api' api_key, url = ARGV diff --git a/examples/relationships.rb b/examples/relationships.rb index a198153..97be0f4 100644 --- a/examples/relationships.rb +++ b/examples/relationships.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,7 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'The Ghostbusters movie was filmed in Boston.' +params = DocumentParameters.new(content: 'The Ghostbusters movie was filmed in Boston.') response = rosette_api.get_relationships(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/sentences.rb b/examples/sentences.rb index 7077eb8..9dbc289 100644 --- a/examples/sentences.rb +++ b/examples/sentences.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV diff --git a/examples/sentiment.rb b/examples/sentiment.rb index 08ce3c8..bc79f66 100644 --- a/examples/sentiment.rb +++ b/examples/sentiment.rb @@ -1,6 +1,6 @@ require 'tempfile' -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -10,7 +10,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new + file = Tempfile.new(%w(foo .html)) sentiment_text_data = 'New Ghostbusters Film

Original Ghostbuster Dan ' \ 'Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new ' \ @@ -19,7 +19,6 @@ '.

' file.write(sentiment_text_data) file.close -params.file_path = file.path -params.language = 'eng' +params = DocumentParameters.new(file_path: file.path, language: 'eng') response = rosette_api.get_sentiment(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/tokens.rb b/examples/tokens.rb index d40b599..fa7dff6 100644 --- a/examples/tokens.rb +++ b/examples/tokens.rb @@ -1,5 +1,5 @@ -require '../rosette_api' -require '../document_parameters' +require '../rosette_api/rosette_api' +require '../rosette_api/document_parameters' api_key, url = ARGV @@ -9,7 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = '北京大学生物系主任办公室内部会议' +params = DocumentParameters.new(content: '北京大学生物系主任办公室内部会议') response = rosette_api.get_tokens(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/name_parameter.rb b/name_parameter.rb deleted file mode 100644 index bbc8534..0000000 --- a/name_parameter.rb +++ /dev/null @@ -1,33 +0,0 @@ -class NameParameter - attr_accessor :entity_type, - :language, - :script, - :text - - def initialize(text, option = {}) - options = { - 'entity_type' => nil, - 'language' => nil, - 'script' => nil - }.update options - @text = text - @entity_type = options['entity_type'] - @language = options['language'] - @script = options['script'] - end - - def load_param - self.to_hash.select { |key, value| !value.nil? } - .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } - .to_h - end - - def to_hash - { - 'entity_type' => @entity_type, - 'language' => @language, - 'script' => @script, - 'text' => @text - } - end -end diff --git a/name_translation_parameters.rb b/name_translation_parameters.rb deleted file mode 100644 index 456e1e7..0000000 --- a/name_translation_parameters.rb +++ /dev/null @@ -1,51 +0,0 @@ -require_relative 'rosette_api_error' - -class NameTranslationParameters - attr_accessor :entity_type, - :name, - :source_language_of_origin, - :source_language_of_use, - :source_script, - :target_language, - :target_scheme, - :target_script - - def initialize(name, options = {}) - options = { - 'entity_type' => nil, - 'source_language_of_origin' => nil, - 'source_language_of_use' => nil, - 'source_script' => nil, - 'target_language' => nil, - 'target_scheme' => nil, - 'target_script' => nil - }.update options - @name = name - @entity_type = options['entity_type'] - @source_language_of_origin = options['source_language_of_origin'] - @source_language_of_use = options['source_language_of_use'] - @source_script = options['source_script'] - @target_language = options['target_language'] - @target_scheme = options['target_scheme'] - @target_script = options['target_script'] - end - - def load_params - self.to_hash.select { |key, value| !value.nil? } - .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } - .to_h - end - - def to_hash - { - 'entity_type' => @entity_type, - 'name' => @name, - 'source_language_of_origin' => @source_language_of_origin, - 'source_language_of_use' => @source_language_of_use, - 'source_script' => @source_script, - 'target_language' => @target_language, - 'target_scheme' => @target_scheme, - 'target_script' => @target_script - } - end -end diff --git a/bad_request_error.rb b/rosette_api/bad_request_error.rb similarity index 72% rename from bad_request_error.rb rename to rosette_api/bad_request_error.rb index 3d585d5..91d19a1 100644 --- a/bad_request_error.rb +++ b/rosette_api/bad_request_error.rb @@ -1,5 +1,6 @@ require_relative 'rosette_api_error' +# This class represents badRequest Rosette API errors. class BadRequestError < RosetteAPIError def initialize(message) super 'badRequest', message diff --git a/bad_request_format_error.rb b/rosette_api/bad_request_format_error.rb similarity index 70% rename from bad_request_format_error.rb rename to rosette_api/bad_request_format_error.rb index 3627d25..9b5ed59 100644 --- a/bad_request_format_error.rb +++ b/rosette_api/bad_request_format_error.rb @@ -1,5 +1,6 @@ require_relative 'rosette_api_error' +# This class represents the badRequestFormat Rosette API errors. class BadRequestFormatError < RosetteAPIError def initialize(message) super 'badRequestFormat', message diff --git a/document_parameters.rb b/rosette_api/document_parameters.rb similarity index 59% rename from document_parameters.rb rename to rosette_api/document_parameters.rb index df065b5..74bcff7 100644 --- a/document_parameters.rb +++ b/rosette_api/document_parameters.rb @@ -1,21 +1,25 @@ require_relative 'bad_request_format_error' +# This class encapsulates parameters that will be used by most of the endpoints +# with exclusion of name-similarity and name-translation. class DocumentParameters attr_accessor :content, :content_uri, :file_path, :language def initialize(options = {}) options = { - 'content' => nil, - 'content_uri' => nil, - 'file_path' => nil, - 'language' => nil + content: nil, + content_uri: nil, + file_path: nil, + language: nil }.update options - @content = options['content'] - @content_uri = options['content_uri'] - @file_path = options['file_path'] - @language = options['language'] + @content = options[:content] + @content_uri = options[:content_uri] + @file_path = options[:file_path] + @language = options[:language] end + # Validates the parameters by checking if there are multiple content sources + # set or no content provided at all. def validate_params if [@content, @content_uri, @file_path].compact.length > 1 raise BadRequestFormatError.new 'The format of the request is invalid: multiple content sources;' \ @@ -26,6 +30,9 @@ def validate_params end end + # Converts this class to Hash with its keys in lower CamelCase + # + # Returns the new Hash def load_params self.validate_params self.to_hash.select { |key, value| !value.nil? } @@ -33,12 +40,15 @@ def load_params .to_h end + # Converts this class to Hash. + # + # Returns the new Hash def to_hash { - 'content' => @content, - 'content_uri' => @content_uri, - 'file_path' => @file_path, - 'language' => @language + content: @content, + content_uri: @content_uri, + file_path: @file_path, + language: @language } end end diff --git a/rosette_api/name_parameter.rb b/rosette_api/name_parameter.rb new file mode 100644 index 0000000..f05c1a5 --- /dev/null +++ b/rosette_api/name_parameter.rb @@ -0,0 +1,40 @@ +# This class represents an entity name in Rosette API. +class NameParameter + attr_accessor :entity_type, + :language, + :script, + :text + + def initialize(text, options = {}) + options = { + entity_type: nil, + language: nil, + script: nil + }.update options + @text = text + @entity_type = options[:entity_type] + @language = options[:language] + @script = options[:script] + end + + # Converts this class to Hash with its keys in lower CamelCase. + # + # Returns the new Hash + def load_param + self.to_hash.select { |key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h + end + + # Converts this class to Hash. + # + # Returns the new Hash + def to_hash + { + entity_type: @entity_type, + language: @language, + script: @script, + text: @text + } + end +end diff --git a/name_similarity_parameters.rb b/rosette_api/name_similarity_parameters.rb similarity index 63% rename from name_similarity_parameters.rb rename to rosette_api/name_similarity_parameters.rb index 57ea177..44efb5a 100644 --- a/name_similarity_parameters.rb +++ b/rosette_api/name_similarity_parameters.rb @@ -1,6 +1,8 @@ require_relative 'bad_request_error' require_relative 'name_parameter' +# This class encapsulates parameters that are needed for name-similarity in +# Rosette API. class NameSimilarityParameters attr_accessor :name1, :name2 @@ -9,6 +11,8 @@ def initialize(name1, name2) @name2 = name2 end + # Validates the parameters by checking if name1 and name2 are instances of + # a String or NameParameter def validate_params if [String, NameParameter].none? { |clazz| @name1.is_a? clazz } raise BadRequestError.new('name1 option can only be an instance of a String or NameParameter') @@ -17,6 +21,9 @@ def validate_params end end + # Converts this class to Hash with its keys in lower CamelCase + # + # Returns the new Hash def load_params self.validate_params self.to_hash.select { |key, value| !value.nil? } @@ -24,10 +31,13 @@ def load_params .to_h end + # Converts this class to Hash. + # + # Returns the new Hash def to_hash { - 'name1' => @name1.is_a?(NameParameter) ? @name1.load_param : @name1, - 'name2' => @name2.is_a?(NameParameter) ? @name2.load_param : @name2 + name1: @name1.is_a?(NameParameter) ? @name1.load_param : @name1, + name2: @name2.is_a?(NameParameter) ? @name2.load_param : @name2 } end end diff --git a/rosette_api/name_translation_parameters.rb b/rosette_api/name_translation_parameters.rb new file mode 100644 index 0000000..8e88bbf --- /dev/null +++ b/rosette_api/name_translation_parameters.rb @@ -0,0 +1,59 @@ +require_relative 'rosette_api_error' + +# This class encapsulates parameters that are needed for name-translation in +# Rosette API. +class NameTranslationParameters + attr_accessor :entity_type, + :name, + :source_language_of_origin, + :source_language_of_use, + :source_script, + :target_language, + :target_scheme, + :target_script + + def initialize(name, options = {}) + options = { + entity_type: nil, + source_language_of_origin: nil, + source_language_of_use: nil, + source_script: nil, + target_language: nil, + target_scheme: nil, + target_script: nil + }.update options + @name = name + @entity_type = options[:entity_type] + @source_language_of_origin = options[:source_language_of_origin] + @source_language_of_use = options[:source_language_of_use] + @source_script = options[:source_script] + @target_language = options[:target_language] + @target_scheme = options[:target_scheme] + @target_script = options[:target_script] + end + + # Converts this class to Hash with its keys in lower CamelCase + # + # Returns the new Hash + def load_params + self.to_hash.select { |key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h + end + + # Converts this class to Hash. + # + # Returns the new Hash + def to_hash + { + entity_type: @entity_type, + name: @name, + source_language_of_origin: @source_language_of_origin, + source_language_of_use: @source_language_of_use, + source_script: @source_script, + target_language: @target_language, + target_scheme: @target_scheme, + target_script: @target_script + } + end +end diff --git a/request_builder.rb b/rosette_api/request_builder.rb similarity index 74% rename from request_builder.rb rename to rosette_api/request_builder.rb index 49370d9..979d1d2 100644 --- a/request_builder.rb +++ b/rosette_api/request_builder.rb @@ -4,6 +4,7 @@ require 'securerandom' require_relative 'rosette_api_error' +# This class handles all Rosette API requests. class RequestBuilder attr_reader :alternate_url, :params, :user_key @@ -13,6 +14,11 @@ def initialize(user_key, alternate_url, params = {}) @params = params end + # Prepares a plain POST request for Rosette API. + # + # params - Parameters to build the body of the request. + # + # Returns a HTTP connection and the built POST request. def prepare_plain_request(params) uri = URI.parse @alternate_url http = Net::HTTP.new uri.host, uri.port @@ -27,6 +33,11 @@ def prepare_plain_request(params) [http, request] end + # Prepares a multipart/form-data POST request for Rosette API. + # + # params - Parameters to build the body of the request. + # + # Returns a HTTP connection and the built POST request. def prepare_multipart_request(params) begin file = File.open params['filePath'], 'r' @@ -64,6 +75,9 @@ def prepare_multipart_request(params) [http, request] end + # Sends a GET request to Rosette API. + # + # Returns JSON response or raises RosetteAPIError if encountered. def send_get_request uri = URI.parse @alternate_url http = Net::HTTP.new uri.host, uri.port @@ -75,6 +89,9 @@ def send_get_request self.get_response http, request end + # Sends a POST request to Rosette API. + # + # Returns JSON response or raises RosetteAPIError if encountered. def send_post_request if @alternate_url.to_s.include? '/info?clientVersion=' params = '{"body": "version check"}' @@ -91,6 +108,13 @@ def send_post_request self.get_response http, request end + # Gets response from HTTP connection. + # + # http - HTTP connection. + # + # request - Prepared Rosette API request. + # + # Returns JSON response or raises RosetteAPIError if encountered. def get_response(http, request) response = http.request request @@ -101,8 +125,14 @@ def get_response(http, request) else JSON.parse(response.body)['message'] end + code = + if JSON.parse(response.body)['code'].nil? + response.code + else + JSON.parse(response.body)['code'] + end - raise RosetteAPIError.new response.code, message + raise RosetteAPIError.new code, message else response_headers = {} response.header.each_header { |key, value| response_headers[key] = value } diff --git a/rosette_api.rb b/rosette_api/rosette_api.rb similarity index 59% rename from rosette_api.rb rename to rosette_api/rosette_api.rb index 0ddd147..4b94e2b 100644 --- a/rosette_api.rb +++ b/rosette_api/rosette_api.rb @@ -6,6 +6,7 @@ require_relative 'bad_request_error' require_relative 'bad_request_format_error' +# This class allows you to access all Rosette API endpoints. class RosetteAPI BINDING_VERSION = '1.0.2' LANGUAGE_ENDPOINT = '/language' @@ -36,6 +37,7 @@ def initialize(user_key, alternate_url = 'https://api.rosette.com/rest/v1') self.check_version_compatibility end + # Checks binding version compatibility against the Rosette API server. def check_version_compatibility response = RequestBuilder.new(@user_key, @alternate_url + VERSION_CHECK) .send_post_request @@ -47,6 +49,11 @@ def check_version_compatibility end end + # Identifies in which language(s) the input is written. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns list of candidate languages in order of descending confidence. def get_language(params) check_params params @@ -56,6 +63,13 @@ def get_language(params) .send_post_request end + # Extracts parts-of-speech, lemmas (dictionary form), compound components, + # and Han-readings for each token in the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns the lemmas, compound components, Han-readings, and parts-of-speech + # tags of the input for supported languages. def get_morphology_complete(params) check_params params @@ -65,6 +79,12 @@ def get_morphology_complete(params) .send_post_request end + # Extracts compound-components from the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns list of components for each compound word of the input for supported + # languages. def get_compound_components(params) check_params params @@ -74,6 +94,12 @@ def get_compound_components(params) .send_post_request end + # Extracts Han-readings from the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns list of Han-readings which provide pronunciation information for + # Han script, in both Chinese and Japanese input text. def get_han_readings(params) check_params params @@ -83,6 +109,11 @@ def get_han_readings(params) .send_post_request end + # Extracts lemmas from the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns list of lemmas for each token of the input for supported languages. def get_lemmas(params) check_params params @@ -92,6 +123,12 @@ def get_lemmas(params) .send_post_request end + # Extracts parts-of-speech from the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns list of part-of-speech (POS) tags for each of the words of the + # input, depending on the context of how it is used. def get_parts_of_speech(params) check_params params @@ -101,6 +138,11 @@ def get_parts_of_speech(params) .send_post_request end + # Extracts entities from the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns each entity extracted from the input. def get_entities(params) check_params params @@ -110,6 +152,12 @@ def get_entities(params) .send_post_request end + # Extracts entities from the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns list of entities that have been linked to entities in the knowledge + # base. def get_entities_linked(params) check_params params @@ -119,6 +167,11 @@ def get_entities_linked(params) .send_post_request end + # Extracts Tier 1 contextual categories from the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns the contextual categories identified in the input. def get_categories(params) check_params params @@ -128,6 +181,11 @@ def get_categories(params) .send_post_request end + # Extracts relationships from the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns each relationship extracted from the input. def get_relationships(params) check_params params @@ -137,6 +195,11 @@ def get_relationships(params) .send_post_request end + # Analyzes the positive and negative sentiment expressed by the input. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns sentiment analysis results. def get_sentiment(params) check_params params @@ -146,6 +209,11 @@ def get_sentiment(params) .send_post_request end + # Translates a given name to a supported specified language. + # + # params - NameTranslationParameters help build the request body in RequestBuilder + # + # Returns the translation of a name. def name_translation(params) check_params params, 'Expects a NameTranslationParameters type as an argument', NameTranslationParameters @@ -155,6 +223,12 @@ def name_translation(params) .send_post_request end + # Compares two entity names (person, location, or organization) and returns a + # match score from 0 to 1. + # + # params - NameSimilarityParameters help build the request body in RequestBuilder + # + # Returns the confidence score of matching 2 names. def name_similarity(params) check_params params, 'Expects a NameSimilarityParameters type as an argument', NameSimilarityParameters @@ -164,6 +238,11 @@ def name_similarity(params) .send_post_request end + # Divides the input into tokens. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns list of tokens of the input. def get_tokens(params) check_params params @@ -173,6 +252,11 @@ def get_tokens(params) .send_post_request end + # Divides the input into sentences. + # + # params - DocumentParameters help build the request body in RequestBuilder + # + # Returns list of linguistic sentences of the input. def get_sentences(params) check_params params @@ -182,11 +266,15 @@ def get_sentences(params) .send_post_request end + # Gets information about the Rosette API, returns name, version, build number + # and build time. def info RequestBuilder.new(@user_key, @alternate_url + INFO) .send_get_request end + # Pings the Rosette API for a response indicting that the service is + # available. def ping RequestBuilder.new(@user_key, @alternate_url + PING) .send_get_request @@ -194,6 +282,7 @@ def ping private + # Checks that the right parameter type is being passed in def check_params(params, message = 'Expects a DocumentParameters type as an argument', type = DocumentParameters) raise BadRequest.new message unless params.is_a? type end diff --git a/rosette_api_error.rb b/rosette_api/rosette_api_error.rb similarity index 67% rename from rosette_api_error.rb rename to rosette_api/rosette_api_error.rb index ca3857f..701478e 100644 --- a/rosette_api_error.rb +++ b/rosette_api/rosette_api_error.rb @@ -1,3 +1,5 @@ +# This class encapsulates all Rosette API server errors encountered during +# requests. class RosetteAPIError < StandardError attr_accessor :status_code, :message diff --git a/tests/tests_spec.rb b/tests/tests_spec.rb index edd7890..efb32b2 100644 --- a/tests/tests_spec.rb +++ b/tests/tests_spec.rb @@ -1,5 +1,5 @@ # encoding: UTF-8 -require_relative '../rosette_api' +require_relative '../rosette_api/rosette_api' require 'rspec' require 'webmock/rspec' require 'json' From 2722e60ef9c046c310f0b3f42aefe2e03b4aa753 Mon Sep 17 00:00:00 2001 From: fiona Date: Thu, 28 Apr 2016 11:31:58 -0400 Subject: [PATCH 12/42] Added documentation for class attributes --- {examples/docker => docker}/Dockerfile | 2 +- {examples/docker => docker}/README.md | 0 {examples/docker => docker}/run_ruby.sh | 18 +++-- rosette_api/bad_request_error.rb | 2 +- rosette_api/bad_request_format_error.rb | 2 +- rosette_api/document_parameters.rb | 2 +- rosette_api/name_parameter.rb | 2 +- rosette_api/name_similarity_parameters.rb | 2 +- rosette_api/name_translation_parameters.rb | 28 +++++--- rosette_api/request_builder.rb | 16 +++-- rosette_api/rosette_api.rb | 77 +++++++++++++++++----- rosette_api/rosette_api_error.rb | 2 +- 12 files changed, 110 insertions(+), 43 deletions(-) rename {examples/docker => docker}/Dockerfile (97%) rename {examples/docker => docker}/README.md (100%) rename {examples/docker => docker}/run_ruby.sh (85%) diff --git a/examples/docker/Dockerfile b/docker/Dockerfile similarity index 97% rename from examples/docker/Dockerfile rename to docker/Dockerfile index 2ab892b..bc0dc19 100644 --- a/examples/docker/Dockerfile +++ b/docker/Dockerfile @@ -10,7 +10,7 @@ RUN gem install rubysl-securerandom \ rspec \ webmock \ simplecov \ - tomdoc + rdoc RUN mkdir /ruby-dev WORKDIR /ruby-dev diff --git a/examples/docker/README.md b/docker/README.md similarity index 100% rename from examples/docker/README.md rename to docker/README.md diff --git a/examples/docker/run_ruby.sh b/docker/run_ruby.sh similarity index 85% rename from examples/docker/run_ruby.sh rename to docker/run_ruby.sh index 96aef60..49adab9 100644 --- a/examples/docker/run_ruby.sh +++ b/docker/run_ruby.sh @@ -12,6 +12,8 @@ function HELP { echo " API_KEY - Rosette API key (required)" echo " FILENAME - Ruby source file (optional)" echo " ALT_URL - Alternate service URL (optional)" + echo " GIT_USERNAME - Git username where you would like to push regenerated gh-pages (optional)" + echo " VERSION - Build version (optional)" exit 1 } @@ -53,7 +55,7 @@ function runExample() { #------------ End Functions ---------------------------- #Gets API_KEY, FILENAME and ALT_URL if present -while getopts ":API_KEY:FILENAME:ALT_URL" arg; do +while getopts ":API_KEY:FILENAME:ALT_URL:GIT_USERNAME:VERSION" arg; do case "${arg}" in API_KEY) API_KEY=${OPTARG} @@ -67,6 +69,14 @@ while getopts ":API_KEY:FILENAME:ALT_URL" arg; do FILENAME=${OPTARG} usage ;; + GIT_USERNAME) + GIT_USERNAME=${OPTARG} + usage + ;; + VERSION) + VERSION={OPTARG} + usage + ;; esac done @@ -101,10 +111,8 @@ if [ ! -z ${GIT_USERNAME} ] && [ ! -z ${VERSION} ]; then git checkout origin/gh-pages -b gh-pages git branch -d develop #generate gh-pages and set ouput dir to git repo (gh-pages branch) - cd /ruby-dev - for file in *.rb; do - tomdoc -f html ${file} - done + cd /ruby-dev/rosette_api + rdoc -o /ruby/doc cd /ruby git add . git commit -a -m "publish ruby apidocs ${VERSION}" diff --git a/rosette_api/bad_request_error.rb b/rosette_api/bad_request_error.rb index 91d19a1..04a575e 100644 --- a/rosette_api/bad_request_error.rb +++ b/rosette_api/bad_request_error.rb @@ -2,7 +2,7 @@ # This class represents badRequest Rosette API errors. class BadRequestError < RosetteAPIError - def initialize(message) + def initialize(message) #:notnew: super 'badRequest', message end end diff --git a/rosette_api/bad_request_format_error.rb b/rosette_api/bad_request_format_error.rb index 9b5ed59..e72e897 100644 --- a/rosette_api/bad_request_format_error.rb +++ b/rosette_api/bad_request_format_error.rb @@ -2,7 +2,7 @@ # This class represents the badRequestFormat Rosette API errors. class BadRequestFormatError < RosetteAPIError - def initialize(message) + def initialize(message) #:notnew: super 'badRequestFormat', message end end diff --git a/rosette_api/document_parameters.rb b/rosette_api/document_parameters.rb index 74bcff7..00bea94 100644 --- a/rosette_api/document_parameters.rb +++ b/rosette_api/document_parameters.rb @@ -5,7 +5,7 @@ class DocumentParameters attr_accessor :content, :content_uri, :file_path, :language - def initialize(options = {}) + def initialize(options = {}) #:notnew: options = { content: nil, content_uri: nil, diff --git a/rosette_api/name_parameter.rb b/rosette_api/name_parameter.rb index f05c1a5..1c04dc8 100644 --- a/rosette_api/name_parameter.rb +++ b/rosette_api/name_parameter.rb @@ -5,7 +5,7 @@ class NameParameter :script, :text - def initialize(text, options = {}) + def initialize(text, options = {}) #:notnew: options = { entity_type: nil, language: nil, diff --git a/rosette_api/name_similarity_parameters.rb b/rosette_api/name_similarity_parameters.rb index 44efb5a..3c63a91 100644 --- a/rosette_api/name_similarity_parameters.rb +++ b/rosette_api/name_similarity_parameters.rb @@ -6,7 +6,7 @@ class NameSimilarityParameters attr_accessor :name1, :name2 - def initialize(name1, name2) + def initialize(name1, name2) #:notnew: @name1 = name1 @name2 = name2 end diff --git a/rosette_api/name_translation_parameters.rb b/rosette_api/name_translation_parameters.rb index 8e88bbf..ca520c3 100644 --- a/rosette_api/name_translation_parameters.rb +++ b/rosette_api/name_translation_parameters.rb @@ -3,16 +3,24 @@ # This class encapsulates parameters that are needed for name-translation in # Rosette API. class NameTranslationParameters - attr_accessor :entity_type, - :name, - :source_language_of_origin, - :source_language_of_use, - :source_script, - :target_language, - :target_scheme, - :target_script + # name's entity type (PERSON, LOCATION, ORGANIZATION) + attr_accessor :entity_type + # name to translate + attr_accessor :name + # ISO 693-3 code for name's language of use (optional) + attr_accessor :source_language_of_origin + # ISO 15924 code for name's script (optional) + attr_accessor :source_language_of_use + # ISO 15924 code for name's script (optional) + attr_accessor :source_script + # ISO 639-3 code for the translation language + attr_accessor :target_language + # transliteration scheme for the translation (optional) + attr_accessor :target_scheme + # ISO 15924 code for name's script (optional) + attr_accessor :target_script - def initialize(name, options = {}) + def initialize(name, options = {}) #:notnew: options = { entity_type: nil, source_language_of_origin: nil, @@ -22,7 +30,7 @@ def initialize(name, options = {}) target_scheme: nil, target_script: nil }.update options - @name = name + @name = name # name to be translated @entity_type = options[:entity_type] @source_language_of_origin = options[:source_language_of_origin] @source_language_of_use = options[:source_language_of_use] diff --git a/rosette_api/request_builder.rb b/rosette_api/request_builder.rb index 979d1d2..bfb5ea0 100644 --- a/rosette_api/request_builder.rb +++ b/rosette_api/request_builder.rb @@ -8,7 +8,7 @@ class RequestBuilder attr_reader :alternate_url, :params, :user_key - def initialize(user_key, alternate_url, params = {}) + def initialize(user_key, alternate_url, params = {}) #:notnew: @user_key = user_key @alternate_url = alternate_url @params = params @@ -16,7 +16,9 @@ def initialize(user_key, alternate_url, params = {}) # Prepares a plain POST request for Rosette API. # - # params - Parameters to build the body of the request. + # ==== Attributes + # + # * +params+ - Parameters to build the body of the request. # # Returns a HTTP connection and the built POST request. def prepare_plain_request(params) @@ -35,7 +37,9 @@ def prepare_plain_request(params) # Prepares a multipart/form-data POST request for Rosette API. # - # params - Parameters to build the body of the request. + # ==== Attributes + # + # * +params+ - Parameters to build the body of the request. # # Returns a HTTP connection and the built POST request. def prepare_multipart_request(params) @@ -110,9 +114,11 @@ def send_post_request # Gets response from HTTP connection. # - # http - HTTP connection. + # ==== Attributes + # + # * +http+ - HTTP connection. # - # request - Prepared Rosette API request. + # * +request+ - Prepared Rosette API request. # # Returns JSON response or raises RosetteAPIError if encountered. def get_response(http, request) diff --git a/rosette_api/rosette_api.rb b/rosette_api/rosette_api.rb index 4b94e2b..2af525b 100644 --- a/rosette_api/rosette_api.rb +++ b/rosette_api/rosette_api.rb @@ -8,25 +8,40 @@ # This class allows you to access all Rosette API endpoints. class RosetteAPI + # Version of Ruby binding BINDING_VERSION = '1.0.2' + # Rosette API language endpoint LANGUAGE_ENDPOINT = '/language' + # Rosette API morphology endpoint MORPHOLOGY_ENDPOINT = '/morphology' + # Rosette API entities endpoint ENTITIES_ENDPOINT = '/entities' + # Rosette API entities/linked endpoint ENTITIES_LINKED_ENDPOINT= '/entities/linked' + # Rosette API categories endpoint CATEGORIES_ENDPOINT = '/categories' + # Rosette API relationships endpoint RELATIONSHIPS_ENDPOINT = '/relationships' + # Rosette API sentiment endpoint SENTIMENT_ENDPOINT = '/sentiment' + # Rosette API name-translation endpoint NAME_TRANSLATION_ENDPOINT = '/name-translation' + # Rosette API name-similarity endpoint NAME_SIMILARITY_ENDPOINT = '/name-similarity' + # Rosette API tokens endpoint TOKENS_ENDPOINT = '/tokens' + # Rosette API sentences endpoint SENTENCES_ENDPOINT = '/sentences' + # Rosette API info endpoint INFO = '/info' + # Rosette API version check endpoint VERSION_CHECK = '/info?clientVersion=' + BINDING_VERSION + # Rosette API ping endpoint PING = '/ping' attr_accessor :user_key, :alternate_url - def initialize(user_key, alternate_url = 'https://api.rosette.com/rest/v1') + def initialize(user_key, alternate_url = 'https://api.rosette.com/rest/v1') #:notnew: @user_key = user_key @alternate_url = alternate_url @@ -51,7 +66,9 @@ def check_version_compatibility # Identifies in which language(s) the input is written. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns list of candidate languages in order of descending confidence. def get_language(params) @@ -66,7 +83,9 @@ def get_language(params) # Extracts parts-of-speech, lemmas (dictionary form), compound components, # and Han-readings for each token in the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns the lemmas, compound components, Han-readings, and parts-of-speech # tags of the input for supported languages. @@ -81,7 +100,9 @@ def get_morphology_complete(params) # Extracts compound-components from the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns list of components for each compound word of the input for supported # languages. @@ -96,7 +117,9 @@ def get_compound_components(params) # Extracts Han-readings from the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns list of Han-readings which provide pronunciation information for # Han script, in both Chinese and Japanese input text. @@ -111,7 +134,9 @@ def get_han_readings(params) # Extracts lemmas from the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns list of lemmas for each token of the input for supported languages. def get_lemmas(params) @@ -125,7 +150,9 @@ def get_lemmas(params) # Extracts parts-of-speech from the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns list of part-of-speech (POS) tags for each of the words of the # input, depending on the context of how it is used. @@ -140,7 +167,9 @@ def get_parts_of_speech(params) # Extracts entities from the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns each entity extracted from the input. def get_entities(params) @@ -154,7 +183,9 @@ def get_entities(params) # Extracts entities from the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns list of entities that have been linked to entities in the knowledge # base. @@ -169,7 +200,9 @@ def get_entities_linked(params) # Extracts Tier 1 contextual categories from the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns the contextual categories identified in the input. def get_categories(params) @@ -183,7 +216,9 @@ def get_categories(params) # Extracts relationships from the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns each relationship extracted from the input. def get_relationships(params) @@ -197,7 +232,9 @@ def get_relationships(params) # Analyzes the positive and negative sentiment expressed by the input. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns sentiment analysis results. def get_sentiment(params) @@ -211,7 +248,9 @@ def get_sentiment(params) # Translates a given name to a supported specified language. # - # params - NameTranslationParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - NameTranslationParameters helps to build the request body in RequestBuilder. # # Returns the translation of a name. def name_translation(params) @@ -226,7 +265,9 @@ def name_translation(params) # Compares two entity names (person, location, or organization) and returns a # match score from 0 to 1. # - # params - NameSimilarityParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - NameSimilarityParameters helps to build the request body in RequestBuilder. # # Returns the confidence score of matching 2 names. def name_similarity(params) @@ -240,7 +281,9 @@ def name_similarity(params) # Divides the input into tokens. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns list of tokens of the input. def get_tokens(params) @@ -254,7 +297,9 @@ def get_tokens(params) # Divides the input into sentences. # - # params - DocumentParameters help build the request body in RequestBuilder + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. # # Returns list of linguistic sentences of the input. def get_sentences(params) diff --git a/rosette_api/rosette_api_error.rb b/rosette_api/rosette_api_error.rb index 701478e..25c590c 100644 --- a/rosette_api/rosette_api_error.rb +++ b/rosette_api/rosette_api_error.rb @@ -3,7 +3,7 @@ class RosetteAPIError < StandardError attr_accessor :status_code, :message - def initialize(status_code, message) + def initialize(status_code, message) #:notnew: @status_code = status_code @message = message end From db632366ac18a8f4d88d0a1a7b23895d6c109d8c Mon Sep 17 00:00:00 2001 From: fiona Date: Thu, 28 Apr 2016 16:28:12 -0400 Subject: [PATCH 13/42] Reorganized project and added Docker image to run examples against development source --- docker/run_ruby.sh | 5 +-- examples/categories.rb | 4 +-- examples/entities.rb | 4 +-- examples/entities_linked.rb | 6 ++-- examples/info.rb | 2 +- examples/language.rb | 4 +-- examples/morphology_complete.rb | 4 +-- examples/morphology_compound_components.rb | 4 +-- examples/morphology_han_readings.rb | 4 +-- examples/morphology_lemmas.rb | 4 +-- examples/morphology_parts_of_speech.rb | 4 +-- examples/name_similarity.rb | 4 +-- examples/name_translation.rb | 6 ++-- examples/ping.rb | 2 +- examples/relationships.rb | 4 +-- examples/sentences.rb | 4 +-- examples/sentiment.rb | 4 +-- examples/tokens.rb | 4 +-- {rosette_api => lib}/bad_request_error.rb | 2 +- .../bad_request_format_error.rb | 2 +- {rosette_api => lib}/document_parameters.rb | 19 +++++++--- {rosette_api => lib}/name_parameter.rb | 16 +++++---- .../name_similarity_parameters.rb | 22 ++++++++---- .../name_translation_parameters.rb | 33 +++++++++-------- {rosette_api => lib}/request_builder.rb | 35 +++++++++++-------- {rosette_api => lib}/rosette_api.rb | 7 ++-- {rosette_api => lib}/rosette_api_error.rb | 5 ++- tests/tests_spec.rb | 5 ++- 28 files changed, 129 insertions(+), 90 deletions(-) rename {rosette_api => lib}/bad_request_error.rb (68%) rename {rosette_api => lib}/bad_request_format_error.rb (68%) rename {rosette_api => lib}/document_parameters.rb (75%) rename {rosette_api => lib}/name_parameter.rb (69%) rename {rosette_api => lib}/name_similarity_parameters.rb (75%) rename {rosette_api => lib}/name_translation_parameters.rb (69%) rename {rosette_api => lib}/request_builder.rb (86%) rename {rosette_api => lib}/rosette_api.rb (98%) rename {rosette_api => lib}/rosette_api_error.rb (66%) diff --git a/docker/run_ruby.sh b/docker/run_ruby.sh index 49adab9..491db65 100644 --- a/docker/run_ruby.sh +++ b/docker/run_ruby.sh @@ -111,8 +111,9 @@ if [ ! -z ${GIT_USERNAME} ] && [ ! -z ${VERSION} ]; then git checkout origin/gh-pages -b gh-pages git branch -d develop #generate gh-pages and set ouput dir to git repo (gh-pages branch) - cd /ruby-dev/rosette_api - rdoc -o /ruby/doc + cd /ruby-dev/lib + rdoc -o /doc + cp -r -n /doc/. /ruby cd /ruby git add . git commit -a -m "publish ruby apidocs ${VERSION}" diff --git a/examples/categories.rb b/examples/categories.rb index caa6131..4baf1f3 100644 --- a/examples/categories.rb +++ b/examples/categories.rb @@ -1,5 +1,5 @@ -require_relative '../rosette_api/rosette_api' -require_relative '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/entities.rb b/examples/entities.rb index e6f2087..9fa56d2 100644 --- a/examples/entities.rb +++ b/examples/entities.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/entities_linked.rb b/examples/entities_linked.rb index 501473e..714698a 100644 --- a/examples/entities_linked.rb +++ b/examples/entities_linked.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV @@ -9,6 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: 'Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.') +params = DocumentParameters.new(content: 'Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.', genre: 'social-media') response = rosette_api.get_entities_linked(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/info.rb b/examples/info.rb index 4762f39..3f6d8b4 100644 --- a/examples/info.rb +++ b/examples/info.rb @@ -1,4 +1,4 @@ -require '../rosette_api/rosette_api' +require '../lib/rosette_api' api_key, url = ARGV diff --git a/examples/language.rb b/examples/language.rb index 31e1505..ff99318 100644 --- a/examples/language.rb +++ b/examples/language.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/morphology_complete.rb b/examples/morphology_complete.rb index c192a74..6dd7362 100644 --- a/examples/morphology_complete.rb +++ b/examples/morphology_complete.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/morphology_compound_components.rb b/examples/morphology_compound_components.rb index 05f7af1..ac97940 100644 --- a/examples/morphology_compound_components.rb +++ b/examples/morphology_compound_components.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/morphology_han_readings.rb b/examples/morphology_han_readings.rb index 412b002..c4a35f5 100644 --- a/examples/morphology_han_readings.rb +++ b/examples/morphology_han_readings.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/morphology_lemmas.rb b/examples/morphology_lemmas.rb index d45c1ea..fe4b0c1 100644 --- a/examples/morphology_lemmas.rb +++ b/examples/morphology_lemmas.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/morphology_parts_of_speech.rb b/examples/morphology_parts_of_speech.rb index 4653089..c5e9d25 100644 --- a/examples/morphology_parts_of_speech.rb +++ b/examples/morphology_parts_of_speech.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/name_similarity.rb b/examples/name_similarity.rb index b9f267a..69c7686 100644 --- a/examples/name_similarity.rb +++ b/examples/name_similarity.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/name_similarity_parameters' +require '../lib/rosette_api' +require '../lib/name_similarity_parameters' api_key, url = ARGV diff --git a/examples/name_translation.rb b/examples/name_translation.rb index b1c653c..74167cb 100644 --- a/examples/name_translation.rb +++ b/examples/name_translation.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/name_translation_parameters' +require '../lib/rosette_api' +require '../lib/name_translation_parameters' api_key, url = ARGV @@ -9,6 +9,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف', target_language: 'eng', target_script: 'Latn') +params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف', 'eng', target_script: 'Latn') response = rosette_api.name_translation(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/ping.rb b/examples/ping.rb index 1ac1862..60aba84 100644 --- a/examples/ping.rb +++ b/examples/ping.rb @@ -1,4 +1,4 @@ -require '../rosette_api/rosette_api' +require '../lib/rosette_api' api_key, url = ARGV diff --git a/examples/relationships.rb b/examples/relationships.rb index 97be0f4..cccc9fe 100644 --- a/examples/relationships.rb +++ b/examples/relationships.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/sentences.rb b/examples/sentences.rb index 9dbc289..f4d1604 100644 --- a/examples/sentences.rb +++ b/examples/sentences.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/sentiment.rb b/examples/sentiment.rb index bc79f66..1c2ed6b 100644 --- a/examples/sentiment.rb +++ b/examples/sentiment.rb @@ -1,6 +1,6 @@ require 'tempfile' -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/examples/tokens.rb b/examples/tokens.rb index fa7dff6..232067f 100644 --- a/examples/tokens.rb +++ b/examples/tokens.rb @@ -1,5 +1,5 @@ -require '../rosette_api/rosette_api' -require '../rosette_api/document_parameters' +require '../lib/rosette_api' +require '../lib/document_parameters' api_key, url = ARGV diff --git a/rosette_api/bad_request_error.rb b/lib/bad_request_error.rb similarity index 68% rename from rosette_api/bad_request_error.rb rename to lib/bad_request_error.rb index 04a575e..ec71859 100644 --- a/rosette_api/bad_request_error.rb +++ b/lib/bad_request_error.rb @@ -1,6 +1,6 @@ require_relative 'rosette_api_error' -# This class represents badRequest Rosette API errors. +# This class represents Rosette API errors with badRequest status_code. class BadRequestError < RosetteAPIError def initialize(message) #:notnew: super 'badRequest', message diff --git a/rosette_api/bad_request_format_error.rb b/lib/bad_request_format_error.rb similarity index 68% rename from rosette_api/bad_request_format_error.rb rename to lib/bad_request_format_error.rb index e72e897..71db2b4 100644 --- a/rosette_api/bad_request_format_error.rb +++ b/lib/bad_request_format_error.rb @@ -1,6 +1,6 @@ require_relative 'rosette_api_error' -# This class represents the badRequestFormat Rosette API errors. +# This class represents Rosette API errors with badRequestFormat status_code. class BadRequestFormatError < RosetteAPIError def initialize(message) #:notnew: super 'badRequestFormat', message diff --git a/rosette_api/document_parameters.rb b/lib/document_parameters.rb similarity index 75% rename from rosette_api/document_parameters.rb rename to lib/document_parameters.rb index 00bea94..69bd1ea 100644 --- a/rosette_api/document_parameters.rb +++ b/lib/document_parameters.rb @@ -3,18 +3,29 @@ # This class encapsulates parameters that will be used by most of the endpoints # with exclusion of name-similarity and name-translation. class DocumentParameters - attr_accessor :content, :content_uri, :file_path, :language + # Content to be analyzed (required if no content_uri and file_path) + attr_accessor :content + # URL to retrieve content from and analyze (required if no content and file_path) + attr_accessor :content_uri + # File path of the file to be analyzed (required if no content and content_uri) + attr_accessor :file_path + # genre to categorize the input data + attr_accessor :genre + # ISO 639-3 language code of the provided content (optional) + attr_accessor :language def initialize(options = {}) #:notnew: options = { content: nil, content_uri: nil, file_path: nil, + genre: nil, language: nil }.update options @content = options[:content] @content_uri = options[:content_uri] @file_path = options[:file_path] + @genre = options[:genre] @language = options[:language] end @@ -30,9 +41,9 @@ def validate_params end end - # Converts this class to Hash with its keys in lower CamelCase + # Converts this class to Hash with its keys in lower CamelCase. # - # Returns the new Hash + # Returns the new Hash. def load_params self.validate_params self.to_hash.select { |key, value| !value.nil? } @@ -42,7 +53,7 @@ def load_params # Converts this class to Hash. # - # Returns the new Hash + # Returns the new Hash. def to_hash { content: @content, diff --git a/rosette_api/name_parameter.rb b/lib/name_parameter.rb similarity index 69% rename from rosette_api/name_parameter.rb rename to lib/name_parameter.rb index 1c04dc8..9f317c1 100644 --- a/rosette_api/name_parameter.rb +++ b/lib/name_parameter.rb @@ -1,9 +1,13 @@ # This class represents an entity name in Rosette API. class NameParameter - attr_accessor :entity_type, - :language, - :script, - :text + # Name's entity type (PERSON, LOCATION, ORGANIZATION) (optional) + attr_accessor :entity_type + # ISO 639-3 code of the name's language (optional) + attr_accessor :language + # ISO 15924 code of the name's script (optional) + attr_accessor :script + # Name to be analyzed + attr_accessor :text def initialize(text, options = {}) #:notnew: options = { @@ -19,7 +23,7 @@ def initialize(text, options = {}) #:notnew: # Converts this class to Hash with its keys in lower CamelCase. # - # Returns the new Hash + # Returns the new Hash. def load_param self.to_hash.select { |key, value| !value.nil? } .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } @@ -28,7 +32,7 @@ def load_param # Converts this class to Hash. # - # Returns the new Hash + # Returns the new Hash. def to_hash { entity_type: @entity_type, diff --git a/rosette_api/name_similarity_parameters.rb b/lib/name_similarity_parameters.rb similarity index 75% rename from rosette_api/name_similarity_parameters.rb rename to lib/name_similarity_parameters.rb index 3c63a91..380b02a 100644 --- a/rosette_api/name_similarity_parameters.rb +++ b/lib/name_similarity_parameters.rb @@ -4,15 +4,25 @@ # This class encapsulates parameters that are needed for name-similarity in # Rosette API. class NameSimilarityParameters - attr_accessor :name1, :name2 + # genre to categorize the input data + attr_accessor :genre + # Name to be compared to name2 + attr_accessor :name1 + # Name to be compared to name1 + attr_accessor :name2 - def initialize(name1, name2) #:notnew: + def initialize(name1, name2, options = {}) #:notnew: + options = { + genre: nil, + }.update options + @genre = options[:genre] @name1 = name1 @name2 = name2 + end # Validates the parameters by checking if name1 and name2 are instances of - # a String or NameParameter + # a String or NameParameter. def validate_params if [String, NameParameter].none? { |clazz| @name1.is_a? clazz } raise BadRequestError.new('name1 option can only be an instance of a String or NameParameter') @@ -21,9 +31,9 @@ def validate_params end end - # Converts this class to Hash with its keys in lower CamelCase + # Converts this class to Hash with its keys in lower CamelCase. # - # Returns the new Hash + # Returns the new Hash. def load_params self.validate_params self.to_hash.select { |key, value| !value.nil? } @@ -33,7 +43,7 @@ def load_params # Converts this class to Hash. # - # Returns the new Hash + # Returns the new Hash. def to_hash { name1: @name1.is_a?(NameParameter) ? @name1.load_param : @name1, diff --git a/rosette_api/name_translation_parameters.rb b/lib/name_translation_parameters.rb similarity index 69% rename from rosette_api/name_translation_parameters.rb rename to lib/name_translation_parameters.rb index ca520c3..87d7f9d 100644 --- a/rosette_api/name_translation_parameters.rb +++ b/lib/name_translation_parameters.rb @@ -3,46 +3,49 @@ # This class encapsulates parameters that are needed for name-translation in # Rosette API. class NameTranslationParameters - # name's entity type (PERSON, LOCATION, ORGANIZATION) + # Name's entity type (PERSON, LOCATION, ORGANIZATION) (optional) attr_accessor :entity_type - # name to translate + # genre to categorize the input data + attr_accessor :genre + # Name to translate attr_accessor :name - # ISO 693-3 code for name's language of use (optional) + # ISO 693-3 code of the name's native language the name originates in (optional) attr_accessor :source_language_of_origin - # ISO 15924 code for name's script (optional) + # ISO 693-3 code of the name's language of use (optional) attr_accessor :source_language_of_use - # ISO 15924 code for name's script (optional) + # ISO 15924 code of the name's script (optional) attr_accessor :source_script - # ISO 639-3 code for the translation language + # ISO 639-3 code of the translation language attr_accessor :target_language - # transliteration scheme for the translation (optional) + # Transliteration scheme for the translation (optional) attr_accessor :target_scheme - # ISO 15924 code for name's script (optional) + # ISO 15924 code of name's script (optional) attr_accessor :target_script - def initialize(name, options = {}) #:notnew: + def initialize(name, target_language, options = {}) #:notnew: options = { entity_type: nil, + genre: nil, source_language_of_origin: nil, source_language_of_use: nil, source_script: nil, - target_language: nil, target_scheme: nil, target_script: nil }.update options - @name = name # name to be translated + @name = name @entity_type = options[:entity_type] + @genre = options[:genre] @source_language_of_origin = options[:source_language_of_origin] @source_language_of_use = options[:source_language_of_use] @source_script = options[:source_script] - @target_language = options[:target_language] + @target_language = target_language @target_scheme = options[:target_scheme] @target_script = options[:target_script] end - # Converts this class to Hash with its keys in lower CamelCase + # Converts this class to Hash with its keys in lower CamelCase. # - # Returns the new Hash + # Returns the new Hash. def load_params self.to_hash.select { |key, value| !value.nil? } .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } @@ -51,7 +54,7 @@ def load_params # Converts this class to Hash. # - # Returns the new Hash + # Returns the new Hash. def to_hash { entity_type: @entity_type, diff --git a/rosette_api/request_builder.rb b/lib/request_builder.rb similarity index 86% rename from rosette_api/request_builder.rb rename to lib/request_builder.rb index bfb5ea0..a220fc5 100644 --- a/rosette_api/request_builder.rb +++ b/lib/request_builder.rb @@ -6,7 +6,13 @@ # This class handles all Rosette API requests. class RequestBuilder - attr_reader :alternate_url, :params, :user_key + @@retries = 5 + # Alternate Rosette API URL + attr_reader :alternate_url + # Parameters to build the body of the request from + attr_accessor :params + # Rosette API key + attr_accessor :user_key def initialize(user_key, alternate_url, params = {}) #:notnew: @user_key = user_key @@ -125,20 +131,19 @@ def get_response(http, request) response = http.request request if response.code != '200' - message = - if JSON.parse(response.body)['message'].nil? - response.body - else - JSON.parse(response.body)['message'] - end - code = - if JSON.parse(response.body)['code'].nil? - response.code - else - JSON.parse(response.body)['code'] - end - - raise RosetteAPIError.new code, message + message = JSON.parse(response.body)['message'] + code = JSON.parse(response.body)['code'] + if response.code == '429' + if @@retries != 0 + @@retries = @@retries - 1 + sleep 15 + self.get_response(http, request) + else + raise RosetteAPIError.new code, message + end + else + raise RosetteAPIError.new code, message + end else response_headers = {} response.header.each_header { |key, value| response_headers[key] = value } diff --git a/rosette_api/rosette_api.rb b/lib/rosette_api.rb similarity index 98% rename from rosette_api/rosette_api.rb rename to lib/rosette_api.rb index 2af525b..e2c496c 100644 --- a/rosette_api/rosette_api.rb +++ b/lib/rosette_api.rb @@ -39,7 +39,10 @@ class RosetteAPI # Rosette API ping endpoint PING = '/ping' - attr_accessor :user_key, :alternate_url + # Rosette API key + attr_accessor :user_key + # Alternate Rosette API URL + attr_accessor :alternate_url def initialize(user_key, alternate_url = 'https://api.rosette.com/rest/v1') #:notnew: @user_key = user_key @@ -327,7 +330,7 @@ def ping private - # Checks that the right parameter type is being passed in + # Checks that the right parameter type is being passed in. def check_params(params, message = 'Expects a DocumentParameters type as an argument', type = DocumentParameters) raise BadRequest.new message unless params.is_a? type end diff --git a/rosette_api/rosette_api_error.rb b/lib/rosette_api_error.rb similarity index 66% rename from rosette_api/rosette_api_error.rb rename to lib/rosette_api_error.rb index 25c590c..20f9648 100644 --- a/rosette_api/rosette_api_error.rb +++ b/lib/rosette_api_error.rb @@ -1,7 +1,10 @@ # This class encapsulates all Rosette API server errors encountered during # requests. class RosetteAPIError < StandardError - attr_accessor :status_code, :message + # Rosette API error's status code + attr_accessor :status_code + # Rosette API error's message + attr_accessor :message def initialize(status_code, message) #:notnew: @status_code = status_code diff --git a/tests/tests_spec.rb b/tests/tests_spec.rb index efb32b2..1aff32c 100644 --- a/tests/tests_spec.rb +++ b/tests/tests_spec.rb @@ -1,5 +1,5 @@ # encoding: UTF-8 -require_relative '../rosette_api/rosette_api' +require_relative '../lib/rosette_api' require 'rspec' require 'webmock/rspec' require 'json' @@ -324,8 +324,7 @@ to_return(status: 200, body: {'test': 'name-translation'}.to_json, headers: {}) end it 'test name translation' do - params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8')) - params.target_language = 'eng' + params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8'), 'eng') params.target_script = 'Latn' response = RosetteAPI.new('0123456789').name_translation(params) expect(response).instance_of? Hash From a51e4f04921958ac5ea9dd7ebec6bd1e94dc1cc3 Mon Sep 17 00:00:00 2001 From: fiona Date: Thu, 28 Apr 2016 16:47:04 -0400 Subject: [PATCH 14/42] Updated README.md files --- README.md | 29 +++++++++++++++++++++-------- docker/README.md | 8 +++----- examples/README.md | 13 ++++++------- 3 files changed, 30 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 20e4fc1..cb4f0e3 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,25 @@ ---- -# Ruby Examples for Rosette API ---- +[![Build Status](https://travis-ci.org/rosette-api/ruby.svg?branch=master)](https://travis-ci.org/rosette-api/ruby) -### Summary -This repository provides Ruby script examples for each of the supported Rosette API endpoints. +Ruby client binding for Rosette API +================================== +See the wiki for more information. -### Basic Usage +Installation +------------ -Install Ruby if you haven't already. Instructions can be found [here](https://www.ruby-lang.org/en/documentation/installation/). +`gem install rosette_api` -Once Ruby is installed simply run the example as: `ruby examplefile.rb your_api_key` to see the results. +Basic Usage +----------- + +See [examples](examples) + +API Documentation +----------------- + +See [documentation](http://rosette-api.github.io/ruby) + +Additional Information +---------------------- + +Visit [Rosette API site](https://developer.rosette.com) diff --git a/docker/README.md b/docker/README.md index 596d2b8..b1e8aa7 100644 --- a/docker/README.md +++ b/docker/README.md @@ -2,13 +2,11 @@ # Docker Image for Ruby Examples --- ### Summary -To simplify the running of the Ruby examples, the Dockerfile will build an image. +To simplify the running of the Ruby examples, the Dockerfile will build an image where the examples can be tested against the development source. ### Basic Usage Build the docker image, e.g. `docker build -t basistech/ruby:1.1 .` -Run an example as `docker run -e API_KEY=api-key -v "path-to-example-source:/source" basistech/ruby:1.1` +Run an example as `docker run -e API_KEY=api-key -v "path-to-local-ruby-dir:/source" basistech/ruby:1.1` -To test against a specific source file, add `-e FILENAME=filename` before the `-v` - -Also, to test against an alternate url, add `-e ALT_URL=alternate_url` before the `-v` \ No newline at end of file +To test against a specific source file, add `-e FILENAME=filename` before the `-v`, to test against an alternate url, add `-e ALT_URL=alternate_url`, and optionally if you would like to regenerate gh-pages from the changes made to the development source you can add `-e GIT_USERNAME=git-username -e VERSION=version` before the `-v`. In order to push the gh-pages to git remember to mount .ssh and .gitconfig to the root dir `-v path-to-.ssh-dir:/root/.ssh -v path-to-.gitconfig:/root/.gitconfig`. \ No newline at end of file diff --git a/examples/README.md b/examples/README.md index 63933b5..0b8d603 100644 --- a/examples/README.md +++ b/examples/README.md @@ -19,21 +19,20 @@ To run all of the examples: Each example, when run, prints its output to the console. | File Name | What it does | -| ------------- |------------- | -| base64_input.rb | Gets the entities from a piece of base64 encoded text| | +| ------------- |------------- | | categories.rb | Gets the category of a document at a URL | | entities.rb | Gets the entities from a piece of text | | entities_linked.rb | Gets the linked (to Wikipedia) entities from a piece of text | | info.rb | Gets information about Rosette API | | language.rb | Gets the language of a piece of text | -| matched-name.rb | Gets the similarity score of two names | +| name_similarity.rb | Gets the similarity score of two names | | morphology_complete.rb | Gets the complete morphological analysis of a piece of text| -| morphology_compound-components.rb | Gets the de-compounded words from a piece of text | -| morphology_han-readings.rb | Gets the Chinese words from a piece of text | +| morphology_compound_components.rb | Gets the de-compounded words from a piece of text | +| morphology_han_readings.rb | Gets the Chinese words from a piece of text | | morphology_lemmas.rb | Gets the lemmas of words from a piece of text | -| morphology_parts-of-speech.rb | Gets the part-of-speech tags for words in a piece of text | +| morphology_parts_of_speech.rb | Gets the part-of-speech tags for words in a piece of text | | ping.rb | Pings the Rosette API to check for reachability | | sentences.rb | Gets the sentences from a piece of text | | sentiment.rb | Gets the sentiment of a local file | | tokens.rb | Gets the tokens (words) from a piece of text | -| translated-name.rb | Translates a name from one language to another | +| name_translation.rb | Translates a name from one language to another | From c44f05d2a132f032362532d34b73a4c529b942e5 Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 29 Apr 2016 11:26:30 -0400 Subject: [PATCH 15/42] Updated Gemfile and added Docker image to run examples against published rosette_api gem --- Gemfile | 10 +-- Gemfile.lock | 58 -------------- docker/Dockerfile | 1 - docker/run_ruby.sh | 4 + examples/categories.rb | 3 +- examples/docker/Dockerfile | 19 +++++ examples/docker/README.md | 14 ++++ examples/docker/run_ruby.sh | 92 ++++++++++++++++++++++ examples/entities.rb | 3 +- examples/entities_linked.rb | 3 +- examples/info.rb | 2 +- examples/language.rb | 3 +- examples/morphology_complete.rb | 3 +- examples/morphology_compound_components.rb | 3 +- examples/morphology_han_readings.rb | 3 +- examples/morphology_lemmas.rb | 3 +- examples/morphology_parts_of_speech.rb | 3 +- examples/name_similarity.rb | 3 +- examples/name_translation.rb | 3 +- examples/ping.rb | 2 +- examples/relationships.rb | 3 +- examples/sentences.rb | 3 +- examples/sentiment.rb | 3 +- examples/tokens.rb | 3 +- lib/request_builder.rb | 12 ++- rosette_api.gemspec | 31 ++++++++ tests/tests_spec.rb | 2 +- 27 files changed, 187 insertions(+), 105 deletions(-) delete mode 100644 Gemfile.lock create mode 100644 examples/docker/Dockerfile create mode 100644 examples/docker/README.md create mode 100644 examples/docker/run_ruby.sh create mode 100644 rosette_api.gemspec diff --git a/Gemfile b/Gemfile index 54f17bb..e031810 100644 --- a/Gemfile +++ b/Gemfile @@ -1,15 +1,7 @@ source "https://rubygems.org" -gem 'rubygems-update', '2.6.3' gem 'rubysl-securerandom', '2.0.0' -gem 'safe_yaml', '1.0.4' -gem 'simplecov', '0.11.2' -gem 'simplecov-html', '0.10.0' +gem 'rdoc', '4.2.2' gem 'rspec', '3.4.0', group: [:test] -gem 'rspec-core', '3.4.4', group: [:test] -gem 'rspec-expectations', '3.4.0', group: [:test] -gem 'rspec-mocks', '3.4.1', group: [:test] -gem 'rspec-support', '3.4.1', group: [:test] -gem 'test-unit', '3.1.5', group: [:test] gem 'webmock', '1.24.5', group: [:test] diff --git a/Gemfile.lock b/Gemfile.lock deleted file mode 100644 index 7282e9b..0000000 --- a/Gemfile.lock +++ /dev/null @@ -1,58 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - addressable (2.4.0) - crack (0.4.3) - safe_yaml (~> 1.0.0) - diff-lcs (1.2.5) - docile (1.1.5) - hashdiff (0.3.0) - json (1.8.3) - power_assert (0.2.7) - rspec (3.4.0) - rspec-core (~> 3.4.0) - rspec-expectations (~> 3.4.0) - rspec-mocks (~> 3.4.0) - rspec-core (3.4.4) - rspec-support (~> 3.4.0) - rspec-expectations (3.4.0) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.4.0) - rspec-mocks (3.4.1) - diff-lcs (>= 1.2.0, < 2.0) - rspec-support (~> 3.4.0) - rspec-support (3.4.1) - rubygems-update (2.6.3) - rubysl-securerandom (2.0.0) - safe_yaml (1.0.4) - simplecov (0.11.2) - docile (~> 1.1.0) - json (~> 1.8) - simplecov-html (~> 0.10.0) - simplecov-html (0.10.0) - test-unit (3.1.5) - power_assert - webmock (1.24.5) - addressable (>= 2.3.6) - crack (>= 0.3.2) - hashdiff - -PLATFORMS - ruby - -DEPENDENCIES - rspec (= 3.4.0) - rspec-core (= 3.4.4) - rspec-expectations (= 3.4.0) - rspec-mocks (= 3.4.1) - rspec-support (= 3.4.1) - rubygems-update (= 2.6.3) - rubysl-securerandom (= 2.0.0) - safe_yaml (= 1.0.4) - simplecov (= 0.11.2) - simplecov-html (= 0.10.0) - test-unit (= 3.1.5) - webmock (= 1.24.5) - -BUNDLED WITH - 1.11.2 diff --git a/docker/Dockerfile b/docker/Dockerfile index bc0dc19..a3f2e0d 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -9,7 +9,6 @@ RUN apt-get -y update && apt-get install -y \ RUN gem install rubysl-securerandom \ rspec \ webmock \ - simplecov \ rdoc RUN mkdir /ruby-dev diff --git a/docker/run_ruby.sh b/docker/run_ruby.sh index 491db65..e9bee21 100644 --- a/docker/run_ruby.sh +++ b/docker/run_ruby.sh @@ -85,6 +85,10 @@ validateURL #Copy the mounted content in /source to current WORKDIR cp -r -n /source/. . +#Build rosette_api gem +gem build rosette_api.gemspec +gem install ./rosette_api-1.0.0.gem + #Run the examples if [ ! -z ${API_KEY} ]; then checkAPI diff --git a/examples/categories.rb b/examples/categories.rb index 4baf1f3..704a941 100644 --- a/examples/categories.rb +++ b/examples/categories.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/docker/Dockerfile b/examples/docker/Dockerfile new file mode 100644 index 0000000..6c67ebb --- /dev/null +++ b/examples/docker/Dockerfile @@ -0,0 +1,19 @@ +FROM ruby +MAINTAINER Fiona Hasanaj + +# install necessary software +RUN apt-get -y update && apt-get install -y \ + vim \ + git + +RUN gem install rosette_api + +RUN mkdir /ruby +WORKDIR /ruby +COPY run_ruby.sh run_ruby.sh +RUN chmod 0755 run_ruby.sh + +# allow interactive bash inside docker container +CMD ./run_ruby.sh $API_KEY $FILENAME $ALT_URL + +VOLUME ["/source"] diff --git a/examples/docker/README.md b/examples/docker/README.md new file mode 100644 index 0000000..b92cce2 --- /dev/null +++ b/examples/docker/README.md @@ -0,0 +1,14 @@ +--- +# Docker Image for Ruby Examples +--- +### Summary +To simplify the running of the Ruby examples, the Dockerfile will build an image and install the latest rosette_api gem. + +### Basic Usage +Build the docker image, e.g. `docker build -t basistech/ruby:1.1 .` + +Run an example as `docker run -e API_KEY=api-key -v "path-to-example-source:/source" basistech/ruby:1.1` + +To test against a specific source file, add `-e FILENAME=filename` before the `-v` + +Also, to test against an alternate url, add `-e ALT_URL=alternate_url` before the `-v` \ No newline at end of file diff --git a/examples/docker/run_ruby.sh b/examples/docker/run_ruby.sh new file mode 100644 index 0000000..414204b --- /dev/null +++ b/examples/docker/run_ruby.sh @@ -0,0 +1,92 @@ +#!/bin/bash + +ping_url="https://api.rosette.com/rest/v1" +retcode=0 +errors=( "Exception" "processingFailure" ) + +#------------ Start Functions -------------------------- + +#Gets called when the user doesn't provide any args +function HELP { + echo -e "\nusage: source_file.rb API_KEY [ALT_URL]" + echo " API_KEY - Rosette API key (required)" + echo " FILENAME - Ruby source file (optional)" + echo " ALT_URL - Alternate service URL (optional)" + exit 1 +} + +#Checks if Rosette API key is valid +function checkAPI { + match=$(curl "${ping_url}/ping" -H "X-RosetteAPI-Key: ${API_KEY}" | grep -o "forbidden") + if [ ! -z $match ]; then + echo -e "\nInvalid Rosette API Key" + exit 1 + fi +} + +#Checks for valid url +function validateURL() { + match=$(curl "${ping_url}/ping" -H "X-RosetteAPI-Key: ${API_KEY}" | grep -o "Rosette API") + if [ "${match}" = "" ]; then + echo -e "\n${ping_url} server not responding\n" + exit 1 + fi +} + +function runExample() { + echo -e "\n---------- ${1} start -------------" + result="" + if [ -z ${ALT_URL} ]; then + result="$(ruby ${1} ${API_KEY} 2>&1 )" + else + result="$(ruby ${1} ${API_KEY} ${ALT_URL} 2>&1 )" + fi + echo "${result}" + echo -e "\n---------- ${1} end -------------" + for err in "${errors[@]}"; do + if [[ ${result} == *"${err}"* ]]; then + retcode=1 + fi + done +} + +#------------ End Functions ---------------------------- + +#Gets API_KEY, FILENAME and ALT_URL if present +while getopts ":API_KEY:FILENAME:ALT_URL:GIT_USERNAME:VERSION" arg; do + case "${arg}" in + API_KEY) + API_KEY=${OPTARG} + usage + ;; + ALT_URL) + ALT_URL=${OPTARG} + usage + ;; + FILENAME) + FILENAME=${OPTARG} + usage + ;; + esac +done + +validateURL + +#Copy the mounted content in /source to current WORKDIR +cp -r -n /source/. . + +#Run the examples +if [ ! -z ${API_KEY} ]; then + checkAPI + if [ ! -z ${FILENAME} ]; then + runExample ${FILENAME} + else + for file in *.rb; do + runExample ${file} + done + fi +else + HELP +fi + +exit ${retcode} diff --git a/examples/entities.rb b/examples/entities.rb index 9fa56d2..2d68ae2 100644 --- a/examples/entities.rb +++ b/examples/entities.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/entities_linked.rb b/examples/entities_linked.rb index 714698a..2cb697f 100644 --- a/examples/entities_linked.rb +++ b/examples/entities_linked.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/info.rb b/examples/info.rb index 3f6d8b4..a82e022 100644 --- a/examples/info.rb +++ b/examples/info.rb @@ -1,4 +1,4 @@ -require '../lib/rosette_api' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/language.rb b/examples/language.rb index ff99318..29612ab 100644 --- a/examples/language.rb +++ b/examples/language.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/morphology_complete.rb b/examples/morphology_complete.rb index 6dd7362..3803e60 100644 --- a/examples/morphology_complete.rb +++ b/examples/morphology_complete.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/morphology_compound_components.rb b/examples/morphology_compound_components.rb index ac97940..622298f 100644 --- a/examples/morphology_compound_components.rb +++ b/examples/morphology_compound_components.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/morphology_han_readings.rb b/examples/morphology_han_readings.rb index c4a35f5..226535c 100644 --- a/examples/morphology_han_readings.rb +++ b/examples/morphology_han_readings.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/morphology_lemmas.rb b/examples/morphology_lemmas.rb index fe4b0c1..51404ce 100644 --- a/examples/morphology_lemmas.rb +++ b/examples/morphology_lemmas.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/morphology_parts_of_speech.rb b/examples/morphology_parts_of_speech.rb index c5e9d25..464c29b 100644 --- a/examples/morphology_parts_of_speech.rb +++ b/examples/morphology_parts_of_speech.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/name_similarity.rb b/examples/name_similarity.rb index 69c7686..2197a03 100644 --- a/examples/name_similarity.rb +++ b/examples/name_similarity.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/name_similarity_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/name_translation.rb b/examples/name_translation.rb index 74167cb..b88922f 100644 --- a/examples/name_translation.rb +++ b/examples/name_translation.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/name_translation_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/ping.rb b/examples/ping.rb index 60aba84..fc43e18 100644 --- a/examples/ping.rb +++ b/examples/ping.rb @@ -1,4 +1,4 @@ -require '../lib/rosette_api' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/relationships.rb b/examples/relationships.rb index cccc9fe..59bf35f 100644 --- a/examples/relationships.rb +++ b/examples/relationships.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/sentences.rb b/examples/sentences.rb index f4d1604..4a5245b 100644 --- a/examples/sentences.rb +++ b/examples/sentences.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/sentiment.rb b/examples/sentiment.rb index 1c2ed6b..6155ea2 100644 --- a/examples/sentiment.rb +++ b/examples/sentiment.rb @@ -1,6 +1,5 @@ require 'tempfile' -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/tokens.rb b/examples/tokens.rb index 232067f..8be177e 100644 --- a/examples/tokens.rb +++ b/examples/tokens.rb @@ -1,5 +1,4 @@ -require '../lib/rosette_api' -require '../lib/document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/lib/request_builder.rb b/lib/request_builder.rb index a220fc5..7b0355a 100644 --- a/lib/request_builder.rb +++ b/lib/request_builder.rb @@ -28,11 +28,15 @@ def initialize(user_key, alternate_url, params = {}) #:notnew: # # Returns a HTTP connection and the built POST request. def prepare_plain_request(params) - uri = URI.parse @alternate_url - http = Net::HTTP.new uri.host, uri.port - http.use_ssl = uri.scheme == 'https' + begin + uri = URI.parse @alternate_url + http = Net::HTTP.new uri.host, uri.port + http.use_ssl = uri.scheme == 'https' + request = Net::HTTP::Post.new uri.request_uri + rescue => err + raise RosetteAPIError.new 'ConnectionError', 'Failed to establish connection with Rosette API server.' + end - request = Net::HTTP::Post.new uri.request_uri request['X-RosetteAPI-Key'] = @user_key request['Content-Type'] = 'application/json' request['Accept'] = 'application/json' diff --git a/rosette_api.gemspec b/rosette_api.gemspec new file mode 100644 index 0000000..3f54a0a --- /dev/null +++ b/rosette_api.gemspec @@ -0,0 +1,31 @@ +lib = File.expand_path('../lib', __FILE__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) + +Gem::Specification.new do |s| + s.specification_version = 2 if s.respond_to? :specification_version= + s.required_rubygems_version = Gem::Requirement.new('>= 0') if s.respond_to? :required_rubygems_version= + s.rubygems_version = '2.2.2' + s.required_ruby_version = '>= 2.3.0' + + s.name = 'rosette_api' + s.version = '1.0.0' + s.license = 'MIT' + + s.summary = 'Rosette API gem that supports multilingual text-analytics.' + s.description = %q{Rosette API gem} + + + + s.authors = ['Basis Technology Corp'] + s.email = %q{fiona@basistech.com} + s.homepage = %q{https://github.com/rosette-api/ruby} + s.date = %q{2016-04-29} + + all_files = `git ls-files -z`.split("\x0") + s.files = all_files.grep(%r{^(bin|lib)/|^.rubocop.yml$}) + s.test_files = ['tests/tests_spec.rb'] + s.require_paths = ['lib'] + s.default_executable = 'rosette_api' + + s.add_runtime_dependency('rubysl-securerandom', '~> 2.0') +end \ No newline at end of file diff --git a/tests/tests_spec.rb b/tests/tests_spec.rb index 1aff32c..85f3750 100644 --- a/tests/tests_spec.rb +++ b/tests/tests_spec.rb @@ -1,5 +1,5 @@ # encoding: UTF-8 -require_relative '../lib/rosette_api' +require 'rosette_api' require 'rspec' require 'webmock/rspec' require 'json' From a53ef72f286525863d3e164a991742b9ff32c711 Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 29 Apr 2016 12:12:59 -0400 Subject: [PATCH 16/42] Fixed style --- lib/document_parameters.rb | 9 +++++---- lib/name_parameter.rb | 6 +++--- lib/name_similarity_parameters.rb | 9 ++++----- lib/name_translation_parameters.rb | 6 +++--- lib/request_builder.rb | 14 +++++--------- lib/rosette_api.rb | 5 +++-- 6 files changed, 23 insertions(+), 26 deletions(-) diff --git a/lib/document_parameters.rb b/lib/document_parameters.rb index 69bd1ea..631dfcc 100644 --- a/lib/document_parameters.rb +++ b/lib/document_parameters.rb @@ -34,7 +34,8 @@ def initialize(options = {}) #:notnew: def validate_params if [@content, @content_uri, @file_path].compact.length > 1 raise BadRequestFormatError.new 'The format of the request is invalid: multiple content sources;' \ - ' must be one of an attachment, an inline "content" field, or an external "contentUri"' + ' must be one of an attachment, an inline "content" field, or an external' \ + '"contentUri"' elsif [@content, @content_uri, @file_path].all?(&:nil?) raise BadRequestFormatError.new 'The format of the request is invalid: no content provided; must' \ ' be one of an attachment, an inline "content" field, or an external "contentUri"' @@ -46,9 +47,9 @@ def validate_params # Returns the new Hash. def load_params self.validate_params - self.to_hash.select { |key, value| !value.nil? } - .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } - .to_h + self.to_hash.select { |_key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h end # Converts this class to Hash. diff --git a/lib/name_parameter.rb b/lib/name_parameter.rb index 9f317c1..a67b484 100644 --- a/lib/name_parameter.rb +++ b/lib/name_parameter.rb @@ -25,9 +25,9 @@ def initialize(text, options = {}) #:notnew: # # Returns the new Hash. def load_param - self.to_hash.select { |key, value| !value.nil? } - .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } - .to_h + self.to_hash.select { |_key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h end # Converts this class to Hash. diff --git a/lib/name_similarity_parameters.rb b/lib/name_similarity_parameters.rb index 380b02a..5a0b605 100644 --- a/lib/name_similarity_parameters.rb +++ b/lib/name_similarity_parameters.rb @@ -13,12 +13,11 @@ class NameSimilarityParameters def initialize(name1, name2, options = {}) #:notnew: options = { - genre: nil, + genre: nil }.update options @genre = options[:genre] @name1 = name1 @name2 = name2 - end # Validates the parameters by checking if name1 and name2 are instances of @@ -36,9 +35,9 @@ def validate_params # Returns the new Hash. def load_params self.validate_params - self.to_hash.select { |key, value| !value.nil? } - .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } - .to_h + self.to_hash.select { |_key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h end # Converts this class to Hash. diff --git a/lib/name_translation_parameters.rb b/lib/name_translation_parameters.rb index 87d7f9d..6d8827b 100644 --- a/lib/name_translation_parameters.rb +++ b/lib/name_translation_parameters.rb @@ -47,9 +47,9 @@ def initialize(name, target_language, options = {}) #:notnew: # # Returns the new Hash. def load_params - self.to_hash.select { |key, value| !value.nil? } - .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } - .to_h + self.to_hash.select { |_key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h end # Converts this class to Hash. diff --git a/lib/request_builder.rb b/lib/request_builder.rb index 7b0355a..8b127f6 100644 --- a/lib/request_builder.rb +++ b/lib/request_builder.rb @@ -6,7 +6,7 @@ # This class handles all Rosette API requests. class RequestBuilder - @@retries = 5 + @retries = 5 # Alternate Rosette API URL attr_reader :alternate_url # Parameters to build the body of the request from @@ -33,7 +33,7 @@ def prepare_plain_request(params) http = Net::HTTP.new uri.host, uri.port http.use_ssl = uri.scheme == 'https' request = Net::HTTP::Post.new uri.request_uri - rescue => err + rescue raise RosetteAPIError.new 'ConnectionError', 'Failed to establish connection with Rosette API server.' end @@ -107,11 +107,7 @@ def send_get_request # # Returns JSON response or raises RosetteAPIError if encountered. def send_post_request - if @alternate_url.to_s.include? '/info?clientVersion=' - params = '{"body": "version check"}' - else - params = @params - end + params = (@alternate_url.to_s.include? '/info?clientVersion=') ? '{"body": "version check"}' : @params if !params['filePath'].nil? http, request = self.prepare_multipart_request params @@ -138,8 +134,8 @@ def get_response(http, request) message = JSON.parse(response.body)['message'] code = JSON.parse(response.body)['code'] if response.code == '429' - if @@retries != 0 - @@retries = @@retries - 1 + if @retries != 0 + @retries = @retries - 1 sleep 15 self.get_response(http, request) else diff --git a/lib/rosette_api.rb b/lib/rosette_api.rb index e2c496c..9c7ada6 100644 --- a/lib/rosette_api.rb +++ b/lib/rosette_api.rb @@ -17,7 +17,7 @@ class RosetteAPI # Rosette API entities endpoint ENTITIES_ENDPOINT = '/entities' # Rosette API entities/linked endpoint - ENTITIES_LINKED_ENDPOINT= '/entities/linked' + ENTITIES_LINKED_ENDPOINT = '/entities/linked' # Rosette API categories endpoint CATEGORIES_ENDPOINT = '/categories' # Rosette API relationships endpoint @@ -114,7 +114,7 @@ def get_compound_components(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url +MORPHOLOGY_ENDPOINT + '/compound-components', params) + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/compound-components', params) .send_post_request end @@ -335,3 +335,4 @@ def check_params(params, message = 'Expects a DocumentParameters type as an argu raise BadRequest.new message unless params.is_a? type end end + From 2b59b874223e6e132d51d9ea896cbd9fb6ddba6d Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 29 Apr 2016 12:17:10 -0400 Subject: [PATCH 17/42] Added license --- LICENSE | 207 ++++---------------------------------------------------- 1 file changed, 12 insertions(+), 195 deletions(-) diff --git a/LICENSE b/LICENSE index 8dada3e..fd207b4 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,18 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ +Basis Technology Corp - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +Copyright (C) 2015-2015 by Basis Technology Corp and the contributors - 1. Definitions. +Complete list of developers available at our web site: - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. +www.basistech.com - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. +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. - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Affero General Public License for more details. - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +You should have received a copy of the GNU Affero General Public License along with this program. +If not, see http://www.gnu.org/licenses/. From 255c755e895fb35ccb762f2dbd3918452cd54d62 Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 29 Apr 2016 12:45:56 -0400 Subject: [PATCH 18/42] Updated email --- lib/request_builder.rb | 2 +- rosette_api.gemspec | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/request_builder.rb b/lib/request_builder.rb index 8b127f6..6e28377 100644 --- a/lib/request_builder.rb +++ b/lib/request_builder.rb @@ -34,7 +34,7 @@ def prepare_plain_request(params) http.use_ssl = uri.scheme == 'https' request = Net::HTTP::Post.new uri.request_uri rescue - raise RosetteAPIError.new 'ConnectionError', 'Failed to establish connection with Rosette API server.' + raise RosetteAPIError.new 'connectionError', 'Failed to establish connection with Rosette API server.' end request['X-RosetteAPI-Key'] = @user_key diff --git a/rosette_api.gemspec b/rosette_api.gemspec index 3f54a0a..296f2b6 100644 --- a/rosette_api.gemspec +++ b/rosette_api.gemspec @@ -17,7 +17,7 @@ Gem::Specification.new do |s| s.authors = ['Basis Technology Corp'] - s.email = %q{fiona@basistech.com} + s.email = %q{support@rosette.com} s.homepage = %q{https://github.com/rosette-api/ruby} s.date = %q{2016-04-29} From 38cfff90913e65b6536506b674ddcd9cb3c296de Mon Sep 17 00:00:00 2001 From: fiona Date: Fri, 29 Apr 2016 15:00:22 -0400 Subject: [PATCH 19/42] Updated .gemspec for 1.0.1 binding version --- docker/run_ruby.sh | 2 +- rosette_api.gemspec | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docker/run_ruby.sh b/docker/run_ruby.sh index e9bee21..eff2c77 100644 --- a/docker/run_ruby.sh +++ b/docker/run_ruby.sh @@ -87,7 +87,7 @@ cp -r -n /source/. . #Build rosette_api gem gem build rosette_api.gemspec -gem install ./rosette_api-1.0.0.gem +gem install ./rosette_api-1.0.1.gem #Run the examples if [ ! -z ${API_KEY} ]; then diff --git a/rosette_api.gemspec b/rosette_api.gemspec index 296f2b6..194907b 100644 --- a/rosette_api.gemspec +++ b/rosette_api.gemspec @@ -5,20 +5,20 @@ Gem::Specification.new do |s| s.specification_version = 2 if s.respond_to? :specification_version= s.required_rubygems_version = Gem::Requirement.new('>= 0') if s.respond_to? :required_rubygems_version= s.rubygems_version = '2.2.2' - s.required_ruby_version = '>= 2.3.0' + s.required_ruby_version = '>= 2.0.0' s.name = 'rosette_api' - s.version = '1.0.0' + s.version = '1.0.1' s.license = 'MIT' s.summary = 'Rosette API gem that supports multilingual text-analytics.' - s.description = %q{Rosette API gem} + s.description = %q{A Ruby client binding for the Rosette API, a multilingual text analytics RESTful API.} s.authors = ['Basis Technology Corp'] s.email = %q{support@rosette.com} - s.homepage = %q{https://github.com/rosette-api/ruby} + s.homepage = %q{https://developer.rosette.com/} s.date = %q{2016-04-29} all_files = `git ls-files -z`.split("\x0") From 7f71334ca8bdb95cfad75cd4826cc6bb1bb51042 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 10:26:53 -0400 Subject: [PATCH 20/42] Added travis.yml --- .travis.yml | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..443d3d8 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +rvm: + - 2.0.0 +script: rspec spec \ No newline at end of file From aa2dc63fe716768505b226679376bc2d95825c05 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 11:12:27 -0400 Subject: [PATCH 21/42] Updated .travis.yml --- .travis.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 443d3d8..e3a11d3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,4 @@ +language: ruby rvm: - - 2.0.0 + - 2.0.0-p247 script: rspec spec \ No newline at end of file From 961bcd5b8a440dacc7e9ba765411f61cfef1ea7a Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 12:35:15 -0400 Subject: [PATCH 22/42] Updated .travis.yml --- .travis.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index e3a11d3..ae50524 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,9 @@ language: ruby rvm: - 2.0.0-p247 -script: rspec spec \ No newline at end of file +script: rspec spec + +notifications: + slack: + rooms: + - secure: 4FRaTAAiYyeUvgw2RhmblgbNiJO4wmd34OBgWcwURjP9oVmFfSwR9r1LNCdUGxrPOghexSY2DjXIuvIrfTfi/xYbhHb3Kw7PEAyB8IuBMlKtY4NSFou62S2VhYpxyg58T+C7P2zi0eDnDE06pwTCoGPaimxMZQY91yQ0yPYDPVXbwe5SjEgamzlwGBxlS/0A6w1iCPHg27/iO2hXtdW3oLS2I0F/Q8Q95RBkX9hpg6yqHlTV7jRbSqvQ9OFBqk/tXMHQvhoPDGgCgQDuykJuaAYx7g9d0YL0eEYYOh9B/TJ/kNOwdRFBu5kuQ2/nFS5Z0S3Y3UIhdYjUmm9gSMnwIbYnrW22EqDJLoT9Zi3Gv7Prg/8/fSkWsof7BJTMSuXUqO1AxDGKIxFv9uSF1daZoY+AC1ooU1xDu1nNvWVYPlkwEdDxxmHpFkGT3ESTZYccPovQl8Z5K0I1BBAVdJKDzm07lE6VHbxkKcvK6gG0TN3uLxnSlQtjkfJ+aVMq1kxeVsB9lEsKs9oezsKzzbftMm525aXPg+OAv+31CUFWxvT/p4ps8Q+AV6aZpoPHkpK8VryyNirUeZ/m4m4ebDHhD9vcN+JqE9gzshT+0U3g19SvLiUMQtbuZ2BUvrq2hh2LEGs03AFZaNg9AEUVA1PQRhV5NILyoS/lbiBYJPT39Sg= From dd097baa541f9f960effc7d6007e2a5450185987 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 13:07:24 -0400 Subject: [PATCH 23/42] Merge --- .gitignore | 1 + .ruby-version | 1 + .travis.yml | 9 + Gemfile | 7 + LICENSE | 207 +------------ README.md | 41 +-- docker/Dockerfile | 22 ++ docker/README.md | 12 + docker/run_ruby.sh | 127 ++++++++ document_parameters.rb | 33 -- examples/README.md | 13 +- examples/categories.rb | 6 +- examples/docker/Dockerfile | 7 +- examples/docker/README.md | 2 +- examples/docker/run_ruby.sh | 13 +- examples/entities.rb | 7 +- examples/entities_linked.rb | 7 +- examples/info.rb | 2 +- examples/language.rb | 6 +- examples/morphology_complete.rb | 6 +- examples/morphology_compound_components.rb | 6 +- examples/morphology_han_readings.rb | 6 +- examples/morphology_lemmas.rb | 6 +- examples/morphology_parts_of_speech.rb | 6 +- examples/name_similarity.rb | 7 +- examples/name_translation.rb | 7 +- examples/ping.rb | 2 +- examples/relationships.rb | 6 +- examples/sentences.rb | 3 +- examples/sentiment.rb | 8 +- examples/tokens.rb | 6 +- lib/bad_request_error.rb | 8 + lib/bad_request_format_error.rb | 8 + lib/document_parameters.rb | 66 ++++ lib/name_parameter.rb | 44 +++ lib/name_similarity_parameters.rb | 52 ++++ lib/name_translation_parameters.rb | 70 +++++ lib/request_builder.rb | 155 ++++++++++ lib/rosette_api.rb | 338 +++++++++++++++++++++ lib/rosette_api_error.rb | 13 + name_parameter.rb | 20 -- name_similarity_parameters.rb | 30 -- name_translation_parameters.rb | 28 -- request_builder.rb | 111 ------- rosette_api.gemspec | 31 ++ rosette_api.rb | 186 ------------ rosette_api_error.rb | 8 - tests/{tests.rb => tests_spec.rb} | 231 +++++++------- 48 files changed, 1154 insertions(+), 837 deletions(-) create mode 100644 .ruby-version create mode 100644 .travis.yml create mode 100644 Gemfile create mode 100644 docker/Dockerfile create mode 100644 docker/README.md create mode 100644 docker/run_ruby.sh delete mode 100644 document_parameters.rb create mode 100644 lib/bad_request_error.rb create mode 100644 lib/bad_request_format_error.rb create mode 100644 lib/document_parameters.rb create mode 100644 lib/name_parameter.rb create mode 100644 lib/name_similarity_parameters.rb create mode 100644 lib/name_translation_parameters.rb create mode 100644 lib/request_builder.rb create mode 100644 lib/rosette_api.rb create mode 100644 lib/rosette_api_error.rb delete mode 100644 name_parameter.rb delete mode 100644 name_similarity_parameters.rb delete mode 100644 name_translation_parameters.rb delete mode 100644 request_builder.rb create mode 100644 rosette_api.gemspec delete mode 100644 rosette_api.rb delete mode 100644 rosette_api_error.rb rename tests/{tests.rb => tests_spec.rb} (68%) diff --git a/.gitignore b/.gitignore index a8b1cda..52f966b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +*~ *.gem *.rbc /.config diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 0000000..f962b8e --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-2.3.0@rosette-api diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..ae50524 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,9 @@ +language: ruby +rvm: + - 2.0.0-p247 +script: rspec spec + +notifications: + slack: + rooms: + - secure: 4FRaTAAiYyeUvgw2RhmblgbNiJO4wmd34OBgWcwURjP9oVmFfSwR9r1LNCdUGxrPOghexSY2DjXIuvIrfTfi/xYbhHb3Kw7PEAyB8IuBMlKtY4NSFou62S2VhYpxyg58T+C7P2zi0eDnDE06pwTCoGPaimxMZQY91yQ0yPYDPVXbwe5SjEgamzlwGBxlS/0A6w1iCPHg27/iO2hXtdW3oLS2I0F/Q8Q95RBkX9hpg6yqHlTV7jRbSqvQ9OFBqk/tXMHQvhoPDGgCgQDuykJuaAYx7g9d0YL0eEYYOh9B/TJ/kNOwdRFBu5kuQ2/nFS5Z0S3Y3UIhdYjUmm9gSMnwIbYnrW22EqDJLoT9Zi3Gv7Prg/8/fSkWsof7BJTMSuXUqO1AxDGKIxFv9uSF1daZoY+AC1ooU1xDu1nNvWVYPlkwEdDxxmHpFkGT3ESTZYccPovQl8Z5K0I1BBAVdJKDzm07lE6VHbxkKcvK6gG0TN3uLxnSlQtjkfJ+aVMq1kxeVsB9lEsKs9oezsKzzbftMm525aXPg+OAv+31CUFWxvT/p4ps8Q+AV6aZpoPHkpK8VryyNirUeZ/m4m4ebDHhD9vcN+JqE9gzshT+0U3g19SvLiUMQtbuZ2BUvrq2hh2LEGs03AFZaNg9AEUVA1PQRhV5NILyoS/lbiBYJPT39Sg= diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..e031810 --- /dev/null +++ b/Gemfile @@ -0,0 +1,7 @@ +source "https://rubygems.org" + +gem 'rubysl-securerandom', '2.0.0' +gem 'rdoc', '4.2.2' + +gem 'rspec', '3.4.0', group: [:test] +gem 'webmock', '1.24.5', group: [:test] diff --git a/LICENSE b/LICENSE index 8dada3e..fd207b4 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,18 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ +Basis Technology Corp - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +Copyright (C) 2015-2015 by Basis Technology Corp and the contributors - 1. Definitions. +Complete list of developers available at our web site: - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. +www.basistech.com - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. +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. - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Affero General Public License for more details. - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +You should have received a copy of the GNU Affero General Public License along with this program. +If not, see http://www.gnu.org/licenses/. diff --git a/README.md b/README.md index e0b407e..cb4f0e3 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,25 @@ ---- -# Ruby Binding for Rosette API (Beta) ---- +[![Build Status](https://travis-ci.org/rosette-api/ruby.svg?branch=master)](https://travis-ci.org/rosette-api/ruby) -### Summary -This repository provides a Ruby binding and examples for each of the supported Rosette API endpoints. +Ruby client binding for Rosette API +================================== +See the wiki for more information. -### Basic Usage +Installation +------------ -Install Ruby if you haven't already. Instructions can be found [here](https://www.ruby-lang.org/en/documentation/installation/). +`gem install rosette_api` -Once Ruby is installed simply run the example as: `ruby examplefile.rb your_api_key` to see the results. +Basic Usage +----------- -### Docker +See [examples](examples) -A Dockerfile may be built (examples/docker) to run the examples and unit tests +API Documentation +----------------- -1. `sudo docker build --rm -t ruby-docker .` -1. `cd ruby_root_direcory` -1. `sudo docker run --rm -e API_KEY=valid_api_key -v `pwd`:/source ruby-docker` - -### Testing - -Unit tests are based on RSpec. - -1. Launch the docker image interactively, `sudo docker run --rm -it -e API_KEY=valid_api_key -v `pwd`:/source ruby-docker /bin/bash` -1. `cd tests` -1. `rspec tests.rb` - -### Gem Package - -Coming soon +See [documentation](http://rosette-api.github.io/ruby) +Additional Information +---------------------- +Visit [Rosette API site](https://developer.rosette.com) diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..a3f2e0d --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,22 @@ +FROM ruby +MAINTAINER Fiona Hasanaj + +# install necessary software +RUN apt-get -y update && apt-get install -y \ + vim \ + git + +RUN gem install rubysl-securerandom \ + rspec \ + webmock \ + rdoc + +RUN mkdir /ruby-dev +WORKDIR /ruby-dev +COPY run_ruby.sh run_ruby.sh +RUN chmod 0755 run_ruby.sh + +# allow interactive bash inside docker container +CMD ./run_ruby.sh $API_KEY $FILENAME $ALT_URL + +VOLUME ["/source"] diff --git a/docker/README.md b/docker/README.md new file mode 100644 index 0000000..b1e8aa7 --- /dev/null +++ b/docker/README.md @@ -0,0 +1,12 @@ +--- +# Docker Image for Ruby Examples +--- +### Summary +To simplify the running of the Ruby examples, the Dockerfile will build an image where the examples can be tested against the development source. + +### Basic Usage +Build the docker image, e.g. `docker build -t basistech/ruby:1.1 .` + +Run an example as `docker run -e API_KEY=api-key -v "path-to-local-ruby-dir:/source" basistech/ruby:1.1` + +To test against a specific source file, add `-e FILENAME=filename` before the `-v`, to test against an alternate url, add `-e ALT_URL=alternate_url`, and optionally if you would like to regenerate gh-pages from the changes made to the development source you can add `-e GIT_USERNAME=git-username -e VERSION=version` before the `-v`. In order to push the gh-pages to git remember to mount .ssh and .gitconfig to the root dir `-v path-to-.ssh-dir:/root/.ssh -v path-to-.gitconfig:/root/.gitconfig`. \ No newline at end of file diff --git a/docker/run_ruby.sh b/docker/run_ruby.sh new file mode 100644 index 0000000..eff2c77 --- /dev/null +++ b/docker/run_ruby.sh @@ -0,0 +1,127 @@ +#!/bin/bash + +ping_url="https://api.rosette.com/rest/v1" +retcode=0 +errors=( "Exception" "processingFailure" ) + +#------------ Start Functions -------------------------- + +#Gets called when the user doesn't provide any args +function HELP { + echo -e "\nusage: source_file.rb API_KEY [ALT_URL]" + echo " API_KEY - Rosette API key (required)" + echo " FILENAME - Ruby source file (optional)" + echo " ALT_URL - Alternate service URL (optional)" + echo " GIT_USERNAME - Git username where you would like to push regenerated gh-pages (optional)" + echo " VERSION - Build version (optional)" + exit 1 +} + +#Checks if Rosette API key is valid +function checkAPI { + match=$(curl "${ping_url}/ping" -H "X-RosetteAPI-Key: ${API_KEY}" | grep -o "forbidden") + if [ ! -z $match ]; then + echo -e "\nInvalid Rosette API Key" + exit 1 + fi +} + +#Checks for valid url +function validateURL() { + match=$(curl "${ping_url}/ping" -H "X-RosetteAPI-Key: ${API_KEY}" | grep -o "Rosette API") + if [ "${match}" = "" ]; then + echo -e "\n${ping_url} server not responding\n" + exit 1 + fi +} + +function runExample() { + echo -e "\n---------- ${1} start -------------" + result="" + if [ -z ${ALT_URL} ]; then + result="$(ruby ${1} ${API_KEY} 2>&1 )" + else + result="$(ruby ${1} ${API_KEY} ${ALT_URL} 2>&1 )" + fi + echo "${result}" + echo -e "\n---------- ${1} end -------------" + for err in "${errors[@]}"; do + if [[ ${result} == *"${err}"* ]]; then + retcode=1 + fi + done +} + +#------------ End Functions ---------------------------- + +#Gets API_KEY, FILENAME and ALT_URL if present +while getopts ":API_KEY:FILENAME:ALT_URL:GIT_USERNAME:VERSION" arg; do + case "${arg}" in + API_KEY) + API_KEY=${OPTARG} + usage + ;; + ALT_URL) + ALT_URL=${OPTARG} + usage + ;; + FILENAME) + FILENAME=${OPTARG} + usage + ;; + GIT_USERNAME) + GIT_USERNAME=${OPTARG} + usage + ;; + VERSION) + VERSION={OPTARG} + usage + ;; + esac +done + +validateURL + +#Copy the mounted content in /source to current WORKDIR +cp -r -n /source/. . + +#Build rosette_api gem +gem build rosette_api.gemspec +gem install ./rosette_api-1.0.1.gem + +#Run the examples +if [ ! -z ${API_KEY} ]; then + checkAPI + cd tests + rspec tests_spec.rb + cd ../examples + if [ ! -z ${FILENAME} ]; then + runExample ${FILENAME} + else + for file in *.rb; do + runExample ${file} + done + fi +else + HELP +fi + +#Generate gh-pages and push them to git account (if git username is provided) +if [ ! -z ${GIT_USERNAME} ] && [ ! -z ${VERSION} ]; then + #clone ruby git repo + cd / + git clone git@github.com:${GIT_USERNAME}/ruby.git + cd ruby + git checkout origin/gh-pages -b gh-pages + git branch -d develop + #generate gh-pages and set ouput dir to git repo (gh-pages branch) + cd /ruby-dev/lib + rdoc -o /doc + cp -r -n /doc/. /ruby + cd /ruby + git add . + git commit -a -m "publish ruby apidocs ${VERSION}" + git push +fi + +exit ${retcode} diff --git a/document_parameters.rb b/document_parameters.rb deleted file mode 100644 index a265506..0000000 --- a/document_parameters.rb +++ /dev/null @@ -1,33 +0,0 @@ -require_relative 'rosette_api_error' - -class DocumentParameters - attr_accessor :content, :content_uri, :file_path, :language - - def initialize(content=nil, content_uri=nil, file_path=nil, language=nil) - @content = content - @content_uri = content_uri - @file_path = file_path - @language = language - end - - def validate_params - if [@content, @content_uri, @file_path].count { |attr| !attr.nil? } > 1 - raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: multiple content sources;' \ - ' must be one of an attachment, an inline "content" field, or an external "contentUri"') - elsif [@content, @content_uri, @file_path].count { |attr| attr.nil? } == 3 - raise RosetteAPIError.new('badRequestFormat', 'The format of the request is invalid: no content provided; must' \ - ' be one of an attachment, an inline "content" field, or an external "contentUri"') - end - end - - def load_params - validate_params - self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h - end - - def to_hash - hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } - hash - end -end \ No newline at end of file diff --git a/examples/README.md b/examples/README.md index 63933b5..0b8d603 100644 --- a/examples/README.md +++ b/examples/README.md @@ -19,21 +19,20 @@ To run all of the examples: Each example, when run, prints its output to the console. | File Name | What it does | -| ------------- |------------- | -| base64_input.rb | Gets the entities from a piece of base64 encoded text| | +| ------------- |------------- | | categories.rb | Gets the category of a document at a URL | | entities.rb | Gets the entities from a piece of text | | entities_linked.rb | Gets the linked (to Wikipedia) entities from a piece of text | | info.rb | Gets information about Rosette API | | language.rb | Gets the language of a piece of text | -| matched-name.rb | Gets the similarity score of two names | +| name_similarity.rb | Gets the similarity score of two names | | morphology_complete.rb | Gets the complete morphological analysis of a piece of text| -| morphology_compound-components.rb | Gets the de-compounded words from a piece of text | -| morphology_han-readings.rb | Gets the Chinese words from a piece of text | +| morphology_compound_components.rb | Gets the de-compounded words from a piece of text | +| morphology_han_readings.rb | Gets the Chinese words from a piece of text | | morphology_lemmas.rb | Gets the lemmas of words from a piece of text | -| morphology_parts-of-speech.rb | Gets the part-of-speech tags for words in a piece of text | +| morphology_parts_of_speech.rb | Gets the part-of-speech tags for words in a piece of text | | ping.rb | Pings the Rosette API to check for reachability | | sentences.rb | Gets the sentences from a piece of text | | sentiment.rb | Gets the sentiment of a local file | | tokens.rb | Gets the tokens (words) from a piece of text | -| translated-name.rb | Translates a name from one language to another | +| name_translation.rb | Translates a name from one language to another | diff --git a/examples/categories.rb b/examples/categories.rb index 8083b60..704a941 100644 --- a/examples/categories.rb +++ b/examples/categories.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,7 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content_uri = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' +params = DocumentParameters.new(content_uri: 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/') response = rosette_api.get_categories(params) puts JSON.pretty_generate(response) diff --git a/examples/docker/Dockerfile b/examples/docker/Dockerfile index eed3058..6c67ebb 100644 --- a/examples/docker/Dockerfile +++ b/examples/docker/Dockerfile @@ -6,10 +6,7 @@ RUN apt-get -y update && apt-get install -y \ vim \ git -RUN gem install rubysl-securerandom \ - rspec \ - webmock \ - simplecov +RUN gem install rosette_api RUN mkdir /ruby WORKDIR /ruby @@ -17,6 +14,6 @@ COPY run_ruby.sh run_ruby.sh RUN chmod 0755 run_ruby.sh # allow interactive bash inside docker container -CMD ./run_ruby.sh $API_KEY $FILENAME $ALT_URL +CMD ./run_ruby.sh $API_KEY $FILENAME $ALT_URL VOLUME ["/source"] diff --git a/examples/docker/README.md b/examples/docker/README.md index 596d2b8..b92cce2 100644 --- a/examples/docker/README.md +++ b/examples/docker/README.md @@ -2,7 +2,7 @@ # Docker Image for Ruby Examples --- ### Summary -To simplify the running of the Ruby examples, the Dockerfile will build an image. +To simplify the running of the Ruby examples, the Dockerfile will build an image and install the latest rosette_api gem. ### Basic Usage Build the docker image, e.g. `docker build -t basistech/ruby:1.1 .` diff --git a/examples/docker/run_ruby.sh b/examples/docker/run_ruby.sh index efe2d2d..414204b 100644 --- a/examples/docker/run_ruby.sh +++ b/examples/docker/run_ruby.sh @@ -21,7 +21,7 @@ function checkAPI { if [ ! -z $match ]; then echo -e "\nInvalid Rosette API Key" exit 1 - fi + fi } #Checks for valid url @@ -30,7 +30,7 @@ function validateURL() { if [ "${match}" = "" ]; then echo -e "\n${ping_url} server not responding\n" exit 1 - fi + fi } function runExample() { @@ -43,7 +43,7 @@ function runExample() { fi echo "${result}" echo -e "\n---------- ${1} end -------------" - for err in "${errors[@]}"; do + for err in "${errors[@]}"; do if [[ ${result} == *"${err}"* ]]; then retcode=1 fi @@ -53,7 +53,7 @@ function runExample() { #------------ End Functions ---------------------------- #Gets API_KEY, FILENAME and ALT_URL if present -while getopts ":API_KEY:FILENAME:ALT_URL" arg; do +while getopts ":API_KEY:FILENAME:ALT_URL:GIT_USERNAME:VERSION" arg; do case "${arg}" in API_KEY) API_KEY=${OPTARG} @@ -78,9 +78,6 @@ cp -r -n /source/. . #Run the examples if [ ! -z ${API_KEY} ]; then checkAPI - cd tests - rspec tests.rb - cd ../examples if [ ! -z ${FILENAME} ]; then runExample ${FILENAME} else @@ -88,7 +85,7 @@ if [ ! -z ${API_KEY} ]; then runExample ${file} done fi -else +else HELP fi diff --git a/examples/entities.rb b/examples/entities.rb index f36dd61..2d68ae2 100644 --- a/examples/entities.rb +++ b/examples/entities.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,8 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo ' \ - 'in Boston this… http://dlvr.it/BnsFfS' +params = DocumentParameters.new(content: 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS') response = rosette_api.get_entities(params) puts JSON.pretty_generate(response) diff --git a/examples/entities_linked.rb b/examples/entities_linked.rb index 73668a7..2cb697f 100644 --- a/examples/entities_linked.rb +++ b/examples/entities_linked.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,8 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including ' \ - 'Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' +params = DocumentParameters.new(content: 'Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.', genre: 'social-media') response = rosette_api.get_entities_linked(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/info.rb b/examples/info.rb index 5ada0d8..a82e022 100644 --- a/examples/info.rb +++ b/examples/info.rb @@ -1,4 +1,4 @@ -require '../rosette_api' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/language.rb b/examples/language.rb index dc83754..29612ab 100644 --- a/examples/language.rb +++ b/examples/language.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,7 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'Por favor Señorita, says the man.?' +params = DocumentParameters.new(content: 'Por favor Señorita, says the man.?') response = rosette_api.get_language(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_complete.rb b/examples/morphology_complete.rb index ec50486..3803e60 100644 --- a/examples/morphology_complete.rb +++ b/examples/morphology_complete.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,7 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'The quick brown fox jumped over the lazy dog. Yes he did.' +params = DocumentParameters.new(content: 'The quick brown fox jumped over the lazy dog. Yes he did.') response = rosette_api.get_morphology_complete(params) puts JSON.pretty_generate(response) diff --git a/examples/morphology_compound_components.rb b/examples/morphology_compound_components.rb index 698fb4e..622298f 100644 --- a/examples/morphology_compound_components.rb +++ b/examples/morphology_compound_components.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,7 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'Rechtsschutzversicherungsgesellschaften' +params = DocumentParameters.new(content: 'Rechtsschutzversicherungsgesellschaften') response = rosette_api.get_compound_components(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_han_readings.rb b/examples/morphology_han_readings.rb index 57d1f7d..226535c 100644 --- a/examples/morphology_han_readings.rb +++ b/examples/morphology_han_readings.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,7 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = '北京大学生物系主任办公室内部会议' +params = DocumentParameters.new(content: '北京大学生物系主任办公室内部会议') response = rosette_api.get_han_readings(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_lemmas.rb b/examples/morphology_lemmas.rb index 5fdb4df..51404ce 100644 --- a/examples/morphology_lemmas.rb +++ b/examples/morphology_lemmas.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,7 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" +params = DocumentParameters.new(content: "The fact is that the geese just went back to get a rest and I'm not banking on their return soon") response = rosette_api.get_lemmas(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_parts_of_speech.rb b/examples/morphology_parts_of_speech.rb index ffc2c09..464c29b 100644 --- a/examples/morphology_parts_of_speech.rb +++ b/examples/morphology_parts_of_speech.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,7 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" +params = DocumentParameters.new(content: "The fact is that the geese just went back to get a rest and I'm not banking on their return soon") response = rosette_api.get_parts_of_speech(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_similarity.rb b/examples/name_similarity.rb index 4b7420c..2197a03 100644 --- a/examples/name_similarity.rb +++ b/examples/name_similarity.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../name_similarity_parameters' +require 'rosette_api' api_key, url = ARGV @@ -10,9 +9,7 @@ end -name1 = NameParameter.new('Michael Jackson') -name1.entity_type = 'PERSON' -name1.language = 'eng' +name1 = NameParameter.new('Michael Jackson', entity_type: 'PERSON', language:'eng') params = NameSimilarityParameters.new(name1, '迈克尔·杰克逊') response = rosette_api.name_similarity(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_translation.rb b/examples/name_translation.rb index 5106dac..b88922f 100644 --- a/examples/name_translation.rb +++ b/examples/name_translation.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../name_translation_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,8 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف') -params.target_language = 'eng' -params.target_script = 'Latn' +params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف', 'eng', target_script: 'Latn') response = rosette_api.name_translation(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/ping.rb b/examples/ping.rb index b427d82..fc43e18 100644 --- a/examples/ping.rb +++ b/examples/ping.rb @@ -1,4 +1,4 @@ -require '../rosette_api' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/relationships.rb b/examples/relationships.rb index a198153..59bf35f 100644 --- a/examples/relationships.rb +++ b/examples/relationships.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,7 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'The Ghostbusters movie was filmed in Boston.' +params = DocumentParameters.new(content: 'The Ghostbusters movie was filmed in Boston.') response = rosette_api.get_relationships(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/sentences.rb b/examples/sentences.rb index 7077eb8..4a5245b 100644 --- a/examples/sentences.rb +++ b/examples/sentences.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV diff --git a/examples/sentiment.rb b/examples/sentiment.rb index 08ce3c8..6155ea2 100644 --- a/examples/sentiment.rb +++ b/examples/sentiment.rb @@ -1,6 +1,5 @@ require 'tempfile' -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -10,7 +9,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new + file = Tempfile.new(%w(foo .html)) sentiment_text_data = 'New Ghostbusters Film

Original Ghostbuster Dan ' \ 'Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new ' \ @@ -19,7 +18,6 @@ '.

' file.write(sentiment_text_data) file.close -params.file_path = file.path -params.language = 'eng' +params = DocumentParameters.new(file_path: file.path, language: 'eng') response = rosette_api.get_sentiment(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/tokens.rb b/examples/tokens.rb index d40b599..8be177e 100644 --- a/examples/tokens.rb +++ b/examples/tokens.rb @@ -1,5 +1,4 @@ -require '../rosette_api' -require '../document_parameters' +require 'rosette_api' api_key, url = ARGV @@ -9,7 +8,6 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = '北京大学生物系主任办公室内部会议' +params = DocumentParameters.new(content: '北京大学生物系主任办公室内部会议') response = rosette_api.get_tokens(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/lib/bad_request_error.rb b/lib/bad_request_error.rb new file mode 100644 index 0000000..ec71859 --- /dev/null +++ b/lib/bad_request_error.rb @@ -0,0 +1,8 @@ +require_relative 'rosette_api_error' + +# This class represents Rosette API errors with badRequest status_code. +class BadRequestError < RosetteAPIError + def initialize(message) #:notnew: + super 'badRequest', message + end +end diff --git a/lib/bad_request_format_error.rb b/lib/bad_request_format_error.rb new file mode 100644 index 0000000..71db2b4 --- /dev/null +++ b/lib/bad_request_format_error.rb @@ -0,0 +1,8 @@ +require_relative 'rosette_api_error' + +# This class represents Rosette API errors with badRequestFormat status_code. +class BadRequestFormatError < RosetteAPIError + def initialize(message) #:notnew: + super 'badRequestFormat', message + end +end diff --git a/lib/document_parameters.rb b/lib/document_parameters.rb new file mode 100644 index 0000000..631dfcc --- /dev/null +++ b/lib/document_parameters.rb @@ -0,0 +1,66 @@ +require_relative 'bad_request_format_error' + +# This class encapsulates parameters that will be used by most of the endpoints +# with exclusion of name-similarity and name-translation. +class DocumentParameters + # Content to be analyzed (required if no content_uri and file_path) + attr_accessor :content + # URL to retrieve content from and analyze (required if no content and file_path) + attr_accessor :content_uri + # File path of the file to be analyzed (required if no content and content_uri) + attr_accessor :file_path + # genre to categorize the input data + attr_accessor :genre + # ISO 639-3 language code of the provided content (optional) + attr_accessor :language + + def initialize(options = {}) #:notnew: + options = { + content: nil, + content_uri: nil, + file_path: nil, + genre: nil, + language: nil + }.update options + @content = options[:content] + @content_uri = options[:content_uri] + @file_path = options[:file_path] + @genre = options[:genre] + @language = options[:language] + end + + # Validates the parameters by checking if there are multiple content sources + # set or no content provided at all. + def validate_params + if [@content, @content_uri, @file_path].compact.length > 1 + raise BadRequestFormatError.new 'The format of the request is invalid: multiple content sources;' \ + ' must be one of an attachment, an inline "content" field, or an external' \ + '"contentUri"' + elsif [@content, @content_uri, @file_path].all?(&:nil?) + raise BadRequestFormatError.new 'The format of the request is invalid: no content provided; must' \ + ' be one of an attachment, an inline "content" field, or an external "contentUri"' + end + end + + # Converts this class to Hash with its keys in lower CamelCase. + # + # Returns the new Hash. + def load_params + self.validate_params + self.to_hash.select { |_key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h + end + + # Converts this class to Hash. + # + # Returns the new Hash. + def to_hash + { + content: @content, + content_uri: @content_uri, + file_path: @file_path, + language: @language + } + end +end diff --git a/lib/name_parameter.rb b/lib/name_parameter.rb new file mode 100644 index 0000000..a67b484 --- /dev/null +++ b/lib/name_parameter.rb @@ -0,0 +1,44 @@ +# This class represents an entity name in Rosette API. +class NameParameter + # Name's entity type (PERSON, LOCATION, ORGANIZATION) (optional) + attr_accessor :entity_type + # ISO 639-3 code of the name's language (optional) + attr_accessor :language + # ISO 15924 code of the name's script (optional) + attr_accessor :script + # Name to be analyzed + attr_accessor :text + + def initialize(text, options = {}) #:notnew: + options = { + entity_type: nil, + language: nil, + script: nil + }.update options + @text = text + @entity_type = options[:entity_type] + @language = options[:language] + @script = options[:script] + end + + # Converts this class to Hash with its keys in lower CamelCase. + # + # Returns the new Hash. + def load_param + self.to_hash.select { |_key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h + end + + # Converts this class to Hash. + # + # Returns the new Hash. + def to_hash + { + entity_type: @entity_type, + language: @language, + script: @script, + text: @text + } + end +end diff --git a/lib/name_similarity_parameters.rb b/lib/name_similarity_parameters.rb new file mode 100644 index 0000000..5a0b605 --- /dev/null +++ b/lib/name_similarity_parameters.rb @@ -0,0 +1,52 @@ +require_relative 'bad_request_error' +require_relative 'name_parameter' + +# This class encapsulates parameters that are needed for name-similarity in +# Rosette API. +class NameSimilarityParameters + # genre to categorize the input data + attr_accessor :genre + # Name to be compared to name2 + attr_accessor :name1 + # Name to be compared to name1 + attr_accessor :name2 + + def initialize(name1, name2, options = {}) #:notnew: + options = { + genre: nil + }.update options + @genre = options[:genre] + @name1 = name1 + @name2 = name2 + end + + # Validates the parameters by checking if name1 and name2 are instances of + # a String or NameParameter. + def validate_params + if [String, NameParameter].none? { |clazz| @name1.is_a? clazz } + raise BadRequestError.new('name1 option can only be an instance of a String or NameParameter') + elsif [String, NameParameter].none? { |clazz| @name2.is_a? clazz } + raise BadRequestError.new('name2 option can only be an instance of a String or NameParameter') + end + end + + # Converts this class to Hash with its keys in lower CamelCase. + # + # Returns the new Hash. + def load_params + self.validate_params + self.to_hash.select { |_key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h + end + + # Converts this class to Hash. + # + # Returns the new Hash. + def to_hash + { + name1: @name1.is_a?(NameParameter) ? @name1.load_param : @name1, + name2: @name2.is_a?(NameParameter) ? @name2.load_param : @name2 + } + end +end diff --git a/lib/name_translation_parameters.rb b/lib/name_translation_parameters.rb new file mode 100644 index 0000000..6d8827b --- /dev/null +++ b/lib/name_translation_parameters.rb @@ -0,0 +1,70 @@ +require_relative 'rosette_api_error' + +# This class encapsulates parameters that are needed for name-translation in +# Rosette API. +class NameTranslationParameters + # Name's entity type (PERSON, LOCATION, ORGANIZATION) (optional) + attr_accessor :entity_type + # genre to categorize the input data + attr_accessor :genre + # Name to translate + attr_accessor :name + # ISO 693-3 code of the name's native language the name originates in (optional) + attr_accessor :source_language_of_origin + # ISO 693-3 code of the name's language of use (optional) + attr_accessor :source_language_of_use + # ISO 15924 code of the name's script (optional) + attr_accessor :source_script + # ISO 639-3 code of the translation language + attr_accessor :target_language + # Transliteration scheme for the translation (optional) + attr_accessor :target_scheme + # ISO 15924 code of name's script (optional) + attr_accessor :target_script + + def initialize(name, target_language, options = {}) #:notnew: + options = { + entity_type: nil, + genre: nil, + source_language_of_origin: nil, + source_language_of_use: nil, + source_script: nil, + target_scheme: nil, + target_script: nil + }.update options + @name = name + @entity_type = options[:entity_type] + @genre = options[:genre] + @source_language_of_origin = options[:source_language_of_origin] + @source_language_of_use = options[:source_language_of_use] + @source_script = options[:source_script] + @target_language = target_language + @target_scheme = options[:target_scheme] + @target_script = options[:target_script] + end + + # Converts this class to Hash with its keys in lower CamelCase. + # + # Returns the new Hash. + def load_params + self.to_hash.select { |_key, value| !value.nil? } + .map { |key, value| [key.to_s.split('_').map(&:capitalize).join.sub!(/\D/, &:downcase), value] } + .to_h + end + + # Converts this class to Hash. + # + # Returns the new Hash. + def to_hash + { + entity_type: @entity_type, + name: @name, + source_language_of_origin: @source_language_of_origin, + source_language_of_use: @source_language_of_use, + source_script: @source_script, + target_language: @target_language, + target_scheme: @target_scheme, + target_script: @target_script + } + end +end diff --git a/lib/request_builder.rb b/lib/request_builder.rb new file mode 100644 index 0000000..6e28377 --- /dev/null +++ b/lib/request_builder.rb @@ -0,0 +1,155 @@ +require 'net/http' +require 'net/https' +require 'json' +require 'securerandom' +require_relative 'rosette_api_error' + +# This class handles all Rosette API requests. +class RequestBuilder + @retries = 5 + # Alternate Rosette API URL + attr_reader :alternate_url + # Parameters to build the body of the request from + attr_accessor :params + # Rosette API key + attr_accessor :user_key + + def initialize(user_key, alternate_url, params = {}) #:notnew: + @user_key = user_key + @alternate_url = alternate_url + @params = params + end + + # Prepares a plain POST request for Rosette API. + # + # ==== Attributes + # + # * +params+ - Parameters to build the body of the request. + # + # Returns a HTTP connection and the built POST request. + def prepare_plain_request(params) + begin + uri = URI.parse @alternate_url + http = Net::HTTP.new uri.host, uri.port + http.use_ssl = uri.scheme == 'https' + request = Net::HTTP::Post.new uri.request_uri + rescue + raise RosetteAPIError.new 'connectionError', 'Failed to establish connection with Rosette API server.' + end + + request['X-RosetteAPI-Key'] = @user_key + request['Content-Type'] = 'application/json' + request['Accept'] = 'application/json' + request.body = params.to_json + + [http, request] + end + + # Prepares a multipart/form-data POST request for Rosette API. + # + # ==== Attributes + # + # * +params+ - Parameters to build the body of the request. + # + # Returns a HTTP connection and the built POST request. + def prepare_multipart_request(params) + begin + file = File.open params['filePath'], 'r' + text = file.read + rescue => err + raise err + end + + boundary = SecureRandom.hex + post_body = [] + request_file = params.to_json + + # Add the content data + post_body << "--#{boundary}\r\n" + post_body << "Content-Disposition: form-data; name=\"content\"; filename=\"#{File.basename(file)}\"\r\n" + post_body << "Content-Type: text/plain\r\n\r\n" + post_body << text + + # Add the request data + post_body << "\r\n\r\n--#{boundary}\r\n" + post_body << "Content-Disposition: form-data; name=\"request\"\r\n" + post_body << "Content-Type: application/json\r\n\r\n" + post_body << request_file + post_body << "\r\n\r\n--#{boundary}--\r\n" + + # Create the HTTP objects + uri = URI.parse @alternate_url + http = Net::HTTP.new uri.host, uri.port + http.use_ssl = uri.scheme == 'https' + request = Net::HTTP::Post.new uri.request_uri + request.add_field 'Content-Type', "multipart/form-data; boundary=#{boundary}" + request.add_field 'X-RosetteAPI-Key', @user_key + request.body = post_body.join + + [http, request] + end + + # Sends a GET request to Rosette API. + # + # Returns JSON response or raises RosetteAPIError if encountered. + def send_get_request + uri = URI.parse @alternate_url + http = Net::HTTP.new uri.host, uri.port + http.use_ssl = uri.scheme == 'https' + + request = Net::HTTP::Get.new uri.request_uri + request['X-RosetteAPI-Key'] = @user_key + + self.get_response http, request + end + + # Sends a POST request to Rosette API. + # + # Returns JSON response or raises RosetteAPIError if encountered. + def send_post_request + params = (@alternate_url.to_s.include? '/info?clientVersion=') ? '{"body": "version check"}' : @params + + if !params['filePath'].nil? + http, request = self.prepare_multipart_request params + else + http, request = self.prepare_plain_request params + end + + self.get_response http, request + end + + # Gets response from HTTP connection. + # + # ==== Attributes + # + # * +http+ - HTTP connection. + # + # * +request+ - Prepared Rosette API request. + # + # Returns JSON response or raises RosetteAPIError if encountered. + def get_response(http, request) + response = http.request request + + if response.code != '200' + message = JSON.parse(response.body)['message'] + code = JSON.parse(response.body)['code'] + if response.code == '429' + if @retries != 0 + @retries = @retries - 1 + sleep 15 + self.get_response(http, request) + else + raise RosetteAPIError.new code, message + end + else + raise RosetteAPIError.new code, message + end + else + response_headers = {} + response.header.each_header { |key, value| response_headers[key] = value } + response_headers = { responseHeaders: response_headers } + + JSON.parse(response.body).merge(response_headers) + end + end +end diff --git a/lib/rosette_api.rb b/lib/rosette_api.rb new file mode 100644 index 0000000..9c7ada6 --- /dev/null +++ b/lib/rosette_api.rb @@ -0,0 +1,338 @@ +require_relative 'request_builder' +require_relative 'document_parameters' +require_relative 'name_translation_parameters' +require_relative 'name_similarity_parameters' +require_relative 'rosette_api_error' +require_relative 'bad_request_error' +require_relative 'bad_request_format_error' + +# This class allows you to access all Rosette API endpoints. +class RosetteAPI + # Version of Ruby binding + BINDING_VERSION = '1.0.2' + # Rosette API language endpoint + LANGUAGE_ENDPOINT = '/language' + # Rosette API morphology endpoint + MORPHOLOGY_ENDPOINT = '/morphology' + # Rosette API entities endpoint + ENTITIES_ENDPOINT = '/entities' + # Rosette API entities/linked endpoint + ENTITIES_LINKED_ENDPOINT = '/entities/linked' + # Rosette API categories endpoint + CATEGORIES_ENDPOINT = '/categories' + # Rosette API relationships endpoint + RELATIONSHIPS_ENDPOINT = '/relationships' + # Rosette API sentiment endpoint + SENTIMENT_ENDPOINT = '/sentiment' + # Rosette API name-translation endpoint + NAME_TRANSLATION_ENDPOINT = '/name-translation' + # Rosette API name-similarity endpoint + NAME_SIMILARITY_ENDPOINT = '/name-similarity' + # Rosette API tokens endpoint + TOKENS_ENDPOINT = '/tokens' + # Rosette API sentences endpoint + SENTENCES_ENDPOINT = '/sentences' + # Rosette API info endpoint + INFO = '/info' + # Rosette API version check endpoint + VERSION_CHECK = '/info?clientVersion=' + BINDING_VERSION + # Rosette API ping endpoint + PING = '/ping' + + # Rosette API key + attr_accessor :user_key + # Alternate Rosette API URL + attr_accessor :alternate_url + + def initialize(user_key, alternate_url = 'https://api.rosette.com/rest/v1') #:notnew: + @user_key = user_key + @alternate_url = alternate_url + + if @alternate_url.to_s.end_with?('/') + @alternate_url = alternate_url.to_s.slice(0..-2) + end + + self.check_version_compatibility + end + + # Checks binding version compatibility against the Rosette API server. + def check_version_compatibility + response = RequestBuilder.new(@user_key, @alternate_url + VERSION_CHECK) + .send_post_request + + unless response['versionChecked'] + puts JSON.pretty_generate(response) + + exit + end + end + + # Identifies in which language(s) the input is written. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns list of candidate languages in order of descending confidence. + def get_language(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + LANGUAGE_ENDPOINT, params) + .send_post_request + end + + # Extracts parts-of-speech, lemmas (dictionary form), compound components, + # and Han-readings for each token in the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns the lemmas, compound components, Han-readings, and parts-of-speech + # tags of the input for supported languages. + def get_morphology_complete(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/complete', params) + .send_post_request + end + + # Extracts compound-components from the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns list of components for each compound word of the input for supported + # languages. + def get_compound_components(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/compound-components', params) + .send_post_request + end + + # Extracts Han-readings from the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns list of Han-readings which provide pronunciation information for + # Han script, in both Chinese and Japanese input text. + def get_han_readings(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/han-readings', params) + .send_post_request + end + + # Extracts lemmas from the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns list of lemmas for each token of the input for supported languages. + def get_lemmas(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/lemmas', params) + .send_post_request + end + + # Extracts parts-of-speech from the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns list of part-of-speech (POS) tags for each of the words of the + # input, depending on the context of how it is used. + def get_parts_of_speech(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/parts-of-speech', params) + .send_post_request + end + + # Extracts entities from the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns each entity extracted from the input. + def get_entities(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + ENTITIES_ENDPOINT, params) + .send_post_request + end + + # Extracts entities from the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns list of entities that have been linked to entities in the knowledge + # base. + def get_entities_linked(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + ENTITIES_LINKED_ENDPOINT, params) + .send_post_request + end + + # Extracts Tier 1 contextual categories from the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns the contextual categories identified in the input. + def get_categories(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + CATEGORIES_ENDPOINT, params) + .send_post_request + end + + # Extracts relationships from the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns each relationship extracted from the input. + def get_relationships(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + RELATIONSHIPS_ENDPOINT, params) + .send_post_request + end + + # Analyzes the positive and negative sentiment expressed by the input. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns sentiment analysis results. + def get_sentiment(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + SENTIMENT_ENDPOINT, params) + .send_post_request + end + + # Translates a given name to a supported specified language. + # + # ==== Attributes + # + # * +params+ - NameTranslationParameters helps to build the request body in RequestBuilder. + # + # Returns the translation of a name. + def name_translation(params) + check_params params, 'Expects a NameTranslationParameters type as an argument', NameTranslationParameters + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + NAME_TRANSLATION_ENDPOINT, params) + .send_post_request + end + + # Compares two entity names (person, location, or organization) and returns a + # match score from 0 to 1. + # + # ==== Attributes + # + # * +params+ - NameSimilarityParameters helps to build the request body in RequestBuilder. + # + # Returns the confidence score of matching 2 names. + def name_similarity(params) + check_params params, 'Expects a NameSimilarityParameters type as an argument', NameSimilarityParameters + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + NAME_SIMILARITY_ENDPOINT, params) + .send_post_request + end + + # Divides the input into tokens. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns list of tokens of the input. + def get_tokens(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + TOKENS_ENDPOINT, params) + .send_post_request + end + + # Divides the input into sentences. + # + # ==== Attributes + # + # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # + # Returns list of linguistic sentences of the input. + def get_sentences(params) + check_params params + + params = params.load_params + + RequestBuilder.new(@user_key, @alternate_url + SENTENCES_ENDPOINT, params) + .send_post_request + end + + # Gets information about the Rosette API, returns name, version, build number + # and build time. + def info + RequestBuilder.new(@user_key, @alternate_url + INFO) + .send_get_request + end + + # Pings the Rosette API for a response indicting that the service is + # available. + def ping + RequestBuilder.new(@user_key, @alternate_url + PING) + .send_get_request + end + + private + + # Checks that the right parameter type is being passed in. + def check_params(params, message = 'Expects a DocumentParameters type as an argument', type = DocumentParameters) + raise BadRequest.new message unless params.is_a? type + end +end + diff --git a/lib/rosette_api_error.rb b/lib/rosette_api_error.rb new file mode 100644 index 0000000..20f9648 --- /dev/null +++ b/lib/rosette_api_error.rb @@ -0,0 +1,13 @@ +# This class encapsulates all Rosette API server errors encountered during +# requests. +class RosetteAPIError < StandardError + # Rosette API error's status code + attr_accessor :status_code + # Rosette API error's message + attr_accessor :message + + def initialize(status_code, message) #:notnew: + @status_code = status_code + @message = message + end +end \ No newline at end of file diff --git a/name_parameter.rb b/name_parameter.rb deleted file mode 100644 index 502d0ba..0000000 --- a/name_parameter.rb +++ /dev/null @@ -1,20 +0,0 @@ -class NameParameter - attr_accessor :text, :entity_type, :language, :script - - def initialize(text, entity_type=nil, language=nil, script=nil) - @text = text - @entity_type = entity_type - @language = language - @script = script - end - - def load_param - self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h - end - - def to_hash - hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } - hash - end -end \ No newline at end of file diff --git a/name_similarity_parameters.rb b/name_similarity_parameters.rb deleted file mode 100644 index 6985952..0000000 --- a/name_similarity_parameters.rb +++ /dev/null @@ -1,30 +0,0 @@ -require_relative 'rosette_api_error' -require_relative 'name_parameter' - -class NameSimilarityParameters - attr_accessor :name1, :name2 - - def initialize(name1, name2) - @name1 = name1 - @name2 = name2 - end - - def validate_params - if [String, NameParameter].count { |clazz| @name1.instance_of? clazz } == 0 - raise RosetteAPIError.new('badRequest', 'name1 option can only be an instance of a String or NameParameter') - elsif [String, Hash].count { |clazz| @name2.instance_of? clazz } == 0 - raise RosetteAPIError.new('badRequest', 'name2 option can only be an instance of a String or NameParameter') - end - end - - def load_params - validate_params - self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h - end - - def to_hash - hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var).instance_of?(NameParameter) ? instance_variable_get(var).load_param : instance_variable_get(var) } - hash - end -end \ No newline at end of file diff --git a/name_translation_parameters.rb b/name_translation_parameters.rb deleted file mode 100644 index 6790457..0000000 --- a/name_translation_parameters.rb +++ /dev/null @@ -1,28 +0,0 @@ -require_relative 'rosette_api_error' - -class NameTranslationParameters - attr_accessor :name, :entity_type, :source_language_of_origin, :source_language_of_use, :source_script, - :target_language, :target_scheme, :target_script - - def initialize(name, entity_type=nil, source_language_of_origin=nil, source_language_of_use=nil, source_script=nil, - target_language=nil, target_scheme=nil, target_script=nil) - @name = name - @entity_type = entity_type - @source_language_of_origin = source_language_of_origin - @source_language_of_use = source_language_of_use - @source_script = source_script - @target_language = target_language - @target_scheme = target_scheme - @target_script = target_script - end - - def load_params - self.to_hash.select { |k, v| !v.nil? }.map { |k, v| [k.to_s.split('_').collect(&:capitalize).join.sub!(/\D/, &:downcase), v] }.to_h - end - - def to_hash - hash = {} - instance_variables.each { |var| hash[var.to_s.delete('@')] = instance_variable_get(var) } - hash - end -end \ No newline at end of file diff --git a/request_builder.rb b/request_builder.rb deleted file mode 100644 index 1c9e2eb..0000000 --- a/request_builder.rb +++ /dev/null @@ -1,111 +0,0 @@ -require 'net/http' -require 'net/https' -require 'json' -require 'securerandom' -require_relative 'rosette_api_error' - -class RequestBuilder - attr_reader :user_key, :alternate_url, :params - - def initialize(user_key, alternate_url, params={}) - @user_key = user_key - @alternate_url = alternate_url - @params = params - end - - def prepare_plain_request(params) - uri = URI.parse(@alternate_url) - http = Net::HTTP.new(uri.host, uri.port) - http.use_ssl = true if uri.scheme == 'https' - - request = Net::HTTP::Post.new(uri.request_uri) - request['X-RosetteAPI-Key'] = @user_key - request['Content-Type'] = 'application/json' - request['Accept'] = 'application/json' - request.body = params.to_json - - [http, request] - end - - def prepare_multipart_request(params) - begin - file = File.open(params['filePath'], 'r') - text = file.read - rescue => err - raise err - end - - boundary = SecureRandom.hex - post_body = [] - request_file = params.to_json - - # Add the content data - post_body << "--#{boundary}\r\n" - post_body << "Content-Disposition: form-data; name=\"content\"; filename=\"#{File.basename(file)}\"\r\n" - post_body << "Content-Type: text/plain\r\n\r\n" - post_body << text - - # Add the request data - post_body << "\r\n\r\n--#{boundary}\r\n" - post_body << "Content-Disposition: form-data; name=\"request\"\r\n" - post_body << "Content-Type: application/json\r\n\r\n" - post_body << request_file - post_body << "\r\n\r\n--#{boundary}--\r\n" - - # Create the HTTP objects - uri = URI.parse(@alternate_url) - http = Net::HTTP.new(uri.host, uri.port) - http.use_ssl = true if uri.scheme == 'https' - request = Net::HTTP::Post.new(uri.request_uri) - request.add_field('Content-Type', "multipart/form-data; boundary=#{boundary}") - request.add_field('X-RosetteAPI-Key', @user_key) - request.body = post_body.join - - [http, request] - end - - def send_get_request - uri = URI.parse(@alternate_url) - http = Net::HTTP.new(uri.host, uri.port) - http.use_ssl = true if uri.scheme == 'https' - - request = Net::HTTP::Get.new(uri.request_uri) - request['X-RosetteAPI-Key'] = @user_key - - get_response(http, request) - end - - def send_post_request - if @alternate_url.to_s.include? '/info?clientVersion=' - params = '{"body": "version check"}' - else - params = @params - end - - if !params['filePath'].nil? - http, request = prepare_multipart_request(params) - else - http, request = prepare_plain_request(params) - end - - get_response(http, request) - end - - def get_response(http, request) - response = http.request(request) - if response.code != '200' - message = - if JSON.parse(response.body)['message'].nil? - response.body - else - JSON.parse(response.body)['message'] - end - raise RosetteAPIError.new(response.code, message) - else - response_headers = {} - response.header.each_header { |key, value| response_headers[key] = value } - response_headers = {:responseHeaders => response_headers} - JSON.parse(response.body).merge(response_headers) - end - end -end \ No newline at end of file diff --git a/rosette_api.gemspec b/rosette_api.gemspec new file mode 100644 index 0000000..194907b --- /dev/null +++ b/rosette_api.gemspec @@ -0,0 +1,31 @@ +lib = File.expand_path('../lib', __FILE__) +$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) + +Gem::Specification.new do |s| + s.specification_version = 2 if s.respond_to? :specification_version= + s.required_rubygems_version = Gem::Requirement.new('>= 0') if s.respond_to? :required_rubygems_version= + s.rubygems_version = '2.2.2' + s.required_ruby_version = '>= 2.0.0' + + s.name = 'rosette_api' + s.version = '1.0.1' + s.license = 'MIT' + + s.summary = 'Rosette API gem that supports multilingual text-analytics.' + s.description = %q{A Ruby client binding for the Rosette API, a multilingual text analytics RESTful API.} + + + + s.authors = ['Basis Technology Corp'] + s.email = %q{support@rosette.com} + s.homepage = %q{https://developer.rosette.com/} + s.date = %q{2016-04-29} + + all_files = `git ls-files -z`.split("\x0") + s.files = all_files.grep(%r{^(bin|lib)/|^.rubocop.yml$}) + s.test_files = ['tests/tests_spec.rb'] + s.require_paths = ['lib'] + s.default_executable = 'rosette_api' + + s.add_runtime_dependency('rubysl-securerandom', '~> 2.0') +end \ No newline at end of file diff --git a/rosette_api.rb b/rosette_api.rb deleted file mode 100644 index 4aae6f1..0000000 --- a/rosette_api.rb +++ /dev/null @@ -1,186 +0,0 @@ -require_relative 'request_builder' -require_relative 'document_parameters' -require_relative 'name_translation_parameters' -require_relative 'name_similarity_parameters' -require_relative 'rosette_api_error' - -class RosetteAPI - BINDING_VERSION = '1.0.2' - LANGUAGE_ENDPOINT = '/language' - MORPHOLOGY_ENDPOINT = '/morphology' - ENTITIES_ENDPOINT = '/entities' - ENTITIES_LINKED_ENDPOINT= '/entities/linked' - CATEGORIES_ENDPOINT = '/categories' - RELATIONSHIPS_ENDPOINT = '/relationships' - SENTIMENT_ENDPOINT = '/sentiment' - NAME_TRANSLATION_ENDPOINT = '/name-translation' - NAME_SIMILARITY_ENDPOINT = '/name-similarity' - TOKENS_ENDPOINT = '/tokens' - SENTENCES_ENDPOINT = '/sentences' - INFO = '/info' - VERSION_CHECK = '/info?clientVersion=' + BINDING_VERSION - PING = '/ping' - - attr_accessor :user_key, :alternate_url - - def initialize(user_key, alternate_url='https://api.rosette.com/rest/v1') - @user_key = user_key - @alternate_url = alternate_url - if @alternate_url.to_s.end_with?('/') - @alternate_url = alternate_url.to_s.slice(0..-2) - end - check_version_compatibility - end - - def check_version_compatibility - response = RequestBuilder.new(@user_key, @alternate_url + VERSION_CHECK).send_post_request - unless response['versionChecked'] - puts JSON.pretty_generate(response) - exit - end - end - - def get_language(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + LANGUAGE_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_morphology_complete(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/complete', params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_compound_components(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url +MORPHOLOGY_ENDPOINT + '/compound-components', params) - .send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_han_readings(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/han-readings', params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_lemmas(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/lemmas', params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_parts_of_speech(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/parts-of-speech', params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_entities(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + ENTITIES_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_entities_linked(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + ENTITIES_LINKED_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_categories(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + CATEGORIES_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_relationships(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + RELATIONSHIPS_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_sentiment(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + SENTIMENT_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def name_translation(params) - if params.instance_of? NameTranslationParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + NAME_TRANSLATION_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a NameTranslationParameters type as an argument') - end - end - - def name_similarity(params) - if params.instance_of? NameSimilarityParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + NAME_SIMILARITY_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a NameSimilarityParameters type as an argument') - end - end - - def get_tokens(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + TOKENS_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def get_sentences(params) - if params.instance_of? DocumentParameters - params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + SENTENCES_ENDPOINT, params).send_post_request - else - raise RosetteAPIError.new('badRequest', 'Expects a DocumentParameters type as an argument') - end - end - - def info - RequestBuilder.new(@user_key, @alternate_url + INFO).send_get_request - end - - def ping - RequestBuilder.new(@user_key, @alternate_url + PING).send_get_request - end -end \ No newline at end of file diff --git a/rosette_api_error.rb b/rosette_api_error.rb deleted file mode 100644 index ca3857f..0000000 --- a/rosette_api_error.rb +++ /dev/null @@ -1,8 +0,0 @@ -class RosetteAPIError < StandardError - attr_accessor :status_code, :message - - def initialize(status_code, message) - @status_code = status_code - @message = message - end -end \ No newline at end of file diff --git a/tests/tests.rb b/tests/tests_spec.rb similarity index 68% rename from tests/tests.rb rename to tests/tests_spec.rb index 78ede8a..85f3750 100644 --- a/tests/tests.rb +++ b/tests/tests_spec.rb @@ -1,31 +1,31 @@ # encoding: UTF-8 -require_relative '../rosette_api' +require 'rosette_api' require 'rspec' require 'webmock/rspec' require 'json' -WebMock.disable_net_connect!(:allow_localhost => true) +WebMock.disable_net_connect!(allow_localhost: true) describe RosetteAPI do describe '.get_language' do - request_file = File.open('../mock-data/request/language.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/language.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/language'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'language'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'language'}.to_json, headers: {}) end it 'test language' do params = DocumentParameters.new @@ -38,34 +38,36 @@ params = DocumentParameters.new params.content = 'Por favor Senorita, says the man.?' params.content_uri = 'Por favor Senorita, says the man.?' - expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(RosetteAPIError) + expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(BadRequestFormatError) end it 'badRequestFormat: the format of the request is invalid: no content provided;' do params = DocumentParameters.new - expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(RosetteAPIError) + expect { RosetteAPI.new('0123456789') + .get_language(params) } + .to raise_error(BadRequestFormatError) end end describe '.get_morphology_complete' do - request_file = File.open('../mock-data/request/morphology_complete.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_complete.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/complete'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/complete'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/complete'}.to_json, headers: {}) end it 'test morphology complete' do params = DocumentParameters.new @@ -76,24 +78,24 @@ end describe '.get_compound_components' do - request_file = File.open('../mock-data/request/morphology_compound_components.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_compound_components.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/compound-components'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/compound-components'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/compound-components'}.to_json, headers: {}) end it 'test morphology compound components' do params = DocumentParameters.new @@ -104,24 +106,24 @@ end describe '.get_han_readings' do - request_file = File.open('../mock-data/request/morphology_han_readings.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_han_readings.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/han-readings'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/han-readings'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/han-readings'}.to_json, headers: {}) end it 'test morphology han readings' do params = DocumentParameters.new @@ -132,24 +134,24 @@ end describe '.get_parts_of_speech' do - request_file = File.open('../mock-data/request/morphology_parts_of_speech.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_parts_of_speech.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/parts-of-speech'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/parts-of-speech'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/parts-of-speech'}.to_json, headers: {}) end it 'test morphology parts of speech' do params = DocumentParameters.new @@ -160,24 +162,24 @@ end describe '.get_lemmas' do - request_file = File.open('../mock-data/request/morphology_lemmas.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_lemmas.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/lemmas'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'morphology/lemmas'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'morphology/lemmas'}.to_json, headers: {}) end it 'test morphology lemmas' do params = DocumentParameters.new @@ -188,24 +190,24 @@ end describe '.get_entities' do - request_file = File.open('../mock-data/request/entities.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/entities'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'entities'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'entities'}.to_json, headers: {}) end it 'test entities' do params = DocumentParameters.new @@ -217,24 +219,24 @@ end describe '.get_entities_linked' do - request_file = File.open('../mock-data/request/entities_linked.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities_linked.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/entities/linked'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'entities/linked'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'entities/linked'}.to_json, headers: {}) end it 'test entities linked' do params = DocumentParameters.new @@ -246,24 +248,24 @@ end describe '.get_categories' do - request_file = File.open('../mock-data/request/categories.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/categories.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/categories'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'categories'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'categories'}.to_json, headers: {}) end it 'test categories' do params = DocumentParameters.new @@ -274,24 +276,24 @@ end describe '.get_relationships' do - request_file = File.open('../mock-data/request/relationships.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/relationships.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/relationships'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'relationships'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'relationships'}.to_json, headers: {}) end it 'test relationships' do params = DocumentParameters.new @@ -302,28 +304,27 @@ end describe '.name_translation' do - request_file = File.open('../mock-data/request/name_translation.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_translation.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/name-translation'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'name-translation'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'name-translation'}.to_json, headers: {}) end it 'test name translation' do - params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8')) - params.target_language = 'eng' + params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8'), 'eng') params.target_script = 'Latn' response = RosetteAPI.new('0123456789').name_translation(params) expect(response).instance_of? Hash @@ -331,24 +332,24 @@ end describe '.name_similarity' do - request_file = File.open('../mock-data/request/name_similarity.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_similarity.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/name-similarity'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'name-similarity'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'name-similarity'}.to_json, headers: {}) end it 'test name similarity' do params = NameSimilarityParameters.new('Michael Jackson', '迈克尔·杰克逊') @@ -358,29 +359,29 @@ it 'badRequestFormat: name2 option can only be an instance of a String or NameParameter' do params = NameSimilarityParameters.new('Michael Jackson', 123) - expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(RosetteAPIError) + expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(BadRequestError) end end describe '.get_tokens' do - request_file = File.open('../mock-data/request/tokens.json', :encoding => 'utf-8') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/tokens.json')), encoding: 'utf-8' before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/tokens'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'tokens'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'tokens'}.to_json, headers: {}) end it 'test tokens' do params = DocumentParameters.new @@ -391,24 +392,24 @@ end describe '.get_sentences' do - request_file = File.open('../mock-data/request/sentences.json') + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/sentences.json')) before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/sentences'). - with(:body => request_file.read, - :headers => {'Accept' => 'application/json', + with(body: request_file, + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'sentences'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'sentences'}.to_json, headers: {}) end it 'test sentences' do params = DocumentParameters.new @@ -424,19 +425,19 @@ describe '.info' do before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:get, 'https://api.rosette.com/rest/v1/info'). - with(:headers => {'Accept' => '*/*', + with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'info'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'info'}.to_json, headers: {}) end it 'test info' do response = RosetteAPI.new('0123456789').info @@ -447,19 +448,19 @@ describe '.ping' do before do stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(:body => "\"{\\\"body\\\": \\\"version check\\\"}\"", - :headers => {'Accept' => 'application/json', + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'versionChecked': true}.to_json, :headers => {}) + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:get, 'https://api.rosette.com/rest/v1/ping'). - with(:headers => {'Accept' => '*/*', + with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'User-Agent' => 'Ruby', 'X-Rosetteapi-Key' => '0123456789'}). - to_return(:status => 200, :body => {'test': 'ping'}.to_json, :headers => {}) + to_return(status: 200, body: {'test': 'ping'}.to_json, headers: {}) end it 'test ping' do response = RosetteAPI.new('0123456789').ping From b27ed45c9475c57185ac73157a9e3967b6af378e Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 14:36:37 -0400 Subject: [PATCH 24/42] Updated .travis.yml --- docker/run_ruby.sh | 2 +- rosette_api.gemspec | 2 +- {tests => test}/tests_spec.rb | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename {tests => test}/tests_spec.rb (100%) diff --git a/docker/run_ruby.sh b/docker/run_ruby.sh index eff2c77..a97965d 100644 --- a/docker/run_ruby.sh +++ b/docker/run_ruby.sh @@ -92,7 +92,7 @@ gem install ./rosette_api-1.0.1.gem #Run the examples if [ ! -z ${API_KEY} ]; then checkAPI - cd tests + cd test rspec tests_spec.rb cd ../examples if [ ! -z ${FILENAME} ]; then diff --git a/rosette_api.gemspec b/rosette_api.gemspec index 194907b..acd3f74 100644 --- a/rosette_api.gemspec +++ b/rosette_api.gemspec @@ -23,7 +23,7 @@ Gem::Specification.new do |s| all_files = `git ls-files -z`.split("\x0") s.files = all_files.grep(%r{^(bin|lib)/|^.rubocop.yml$}) - s.test_files = ['tests/tests_spec.rb'] + s.test_files = ['test/tests_spec.rb'] s.require_paths = ['lib'] s.default_executable = 'rosette_api' diff --git a/tests/tests_spec.rb b/test/tests_spec.rb similarity index 100% rename from tests/tests_spec.rb rename to test/tests_spec.rb From 3d7a24f6f375f6d762e6eebbdc93a829b9149167 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 14:54:57 -0400 Subject: [PATCH 25/42] Removed tests folder --- tests/tests_spec.rb | 470 -------------------------------------------- 1 file changed, 470 deletions(-) delete mode 100644 tests/tests_spec.rb diff --git a/tests/tests_spec.rb b/tests/tests_spec.rb deleted file mode 100644 index 85f3750..0000000 --- a/tests/tests_spec.rb +++ /dev/null @@ -1,470 +0,0 @@ -# encoding: UTF-8 -require 'rosette_api' -require 'rspec' -require 'webmock/rspec' -require 'json' -WebMock.disable_net_connect!(allow_localhost: true) - -describe RosetteAPI do - - describe '.get_language' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/language.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/language'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'language'}.to_json, headers: {}) - end - it 'test language' do - params = DocumentParameters.new - params.content = 'Por favor Senorita, says the man.?' - response = RosetteAPI.new('0123456789').get_language(params) - expect(response).instance_of? Hash - end - - it 'badRequestFormat: the format of the request is invalid: multiple content sources' do - params = DocumentParameters.new - params.content = 'Por favor Senorita, says the man.?' - params.content_uri = 'Por favor Senorita, says the man.?' - expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(BadRequestFormatError) - end - - it 'badRequestFormat: the format of the request is invalid: no content provided;' do - params = DocumentParameters.new - expect { RosetteAPI.new('0123456789') - .get_language(params) } - .to raise_error(BadRequestFormatError) - end - end - - describe '.get_morphology_complete' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_complete.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/complete'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/complete'}.to_json, headers: {}) - end - it 'test morphology complete' do - params = DocumentParameters.new - params.content = 'The quick brown fox jumped over the lazy dog. Yes he did.' - response = RosetteAPI.new('0123456789').get_morphology_complete(params) - expect(response).instance_of? Hash - end - end - - describe '.get_compound_components' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_compound_components.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/compound-components'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/compound-components'}.to_json, headers: {}) - end - it 'test morphology compound components' do - params = DocumentParameters.new - params.content = 'Rechtsschutzversicherungsgesellschaften' - response = RosetteAPI.new('0123456789').get_compound_components(params) - expect(response).instance_of? Hash - end - end - - describe '.get_han_readings' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_han_readings.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/han-readings'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/han-readings'}.to_json, headers: {}) - end - it 'test morphology han readings' do - params = DocumentParameters.new - params.content = '北京大学生物系主任办公室内部会议' - response = RosetteAPI.new('0123456789').get_han_readings(params) - expect(response).instance_of? Hash - end - end - - describe '.get_parts_of_speech' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_parts_of_speech.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/parts-of-speech'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/parts-of-speech'}.to_json, headers: {}) - end - it 'test morphology parts of speech' do - params = DocumentParameters.new - params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" - response = RosetteAPI.new('0123456789').get_parts_of_speech(params) - expect(response).instance_of? Hash - end - end - - describe '.get_lemmas' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_lemmas.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/lemmas'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/lemmas'}.to_json, headers: {}) - end - it 'test morphology lemmas' do - params = DocumentParameters.new - params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" - response = RosetteAPI.new('0123456789').get_lemmas(params) - expect(response).instance_of? Hash - end - end - - describe '.get_entities' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/entities'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'entities'}.to_json, headers: {}) - end - it 'test entities' do - params = DocumentParameters.new - params.content = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a' \ - ' cameo in Boston this… http://dlvr.it/BnsFfS' - response = RosetteAPI.new('0123456789').get_entities(params) - expect(response).instance_of? Hash - end - end - - describe '.get_entities_linked' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities_linked.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/entities/linked'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'entities/linked'}.to_json, headers: {}) - end - it 'test entities linked' do - params = DocumentParameters.new - params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including' \ - ' Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' - response = RosetteAPI.new('0123456789').get_entities_linked(params) - expect(response).instance_of? Hash - end - end - - describe '.get_categories' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/categories.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/categories'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'categories'}.to_json, headers: {}) - end - it 'test categories' do - params = DocumentParameters.new - params.content_uri = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' - response = RosetteAPI.new('0123456789').get_categories(params) - expect(response).instance_of? Hash - end - end - - describe '.get_relationships' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/relationships.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/relationships'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'relationships'}.to_json, headers: {}) - end - it 'test relationships' do - params = DocumentParameters.new - params.content = 'The Ghostbusters movie was filmed in Boston.' - response = RosetteAPI.new('0123456789').get_relationships(params) - expect(response).instance_of? Hash - end - end - - describe '.name_translation' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_translation.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/name-translation'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'name-translation'}.to_json, headers: {}) - end - it 'test name translation' do - params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8'), 'eng') - params.target_script = 'Latn' - response = RosetteAPI.new('0123456789').name_translation(params) - expect(response).instance_of? Hash - end - end - - describe '.name_similarity' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_similarity.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/name-similarity'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'name-similarity'}.to_json, headers: {}) - end - it 'test name similarity' do - params = NameSimilarityParameters.new('Michael Jackson', '迈克尔·杰克逊') - response = RosetteAPI.new('0123456789').name_similarity(params) - expect(response).instance_of? Hash - end - - it 'badRequestFormat: name2 option can only be an instance of a String or NameParameter' do - params = NameSimilarityParameters.new('Michael Jackson', 123) - expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(BadRequestError) - end - end - - describe '.get_tokens' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/tokens.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/tokens'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'tokens'}.to_json, headers: {}) - end - it 'test tokens' do - params = DocumentParameters.new - params.content = '北京大学生物系主任办公室内部会议' - response = RosetteAPI.new('0123456789').get_tokens(params) - expect(response).instance_of? Hash - end - end - - describe '.get_sentences' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/sentences.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/sentences'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'sentences'}.to_json, headers: {}) - end - it 'test sentences' do - params = DocumentParameters.new - params.content = 'This land is your land. This land is my land\nFrom California to the New York island;\nFrom' \ - ' the wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was' \ - ' walking that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that' \ - ' golden valley:\nThis land was made for you and me.' - response = RosetteAPI.new('0123456789').get_sentences(params) - expect(response).instance_of? Hash - end - end - - describe '.info' do - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:get, 'https://api.rosette.com/rest/v1/info'). - with(headers: {'Accept' => '*/*', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'info'}.to_json, headers: {}) - end - it 'test info' do - response = RosetteAPI.new('0123456789').info - expect(response).instance_of? Hash - end - end - - describe '.ping' do - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:get, 'https://api.rosette.com/rest/v1/ping'). - with(headers: {'Accept' => '*/*', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'ping'}.to_json, headers: {}) - end - it 'test ping' do - response = RosetteAPI.new('0123456789').ping - expect(response).instance_of? Hash - end - end -end From 27bfcabf7735563589107d912d1298240c549212 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 15:01:54 -0400 Subject: [PATCH 26/42] Revert "Removed tests folder" This reverts commit 3d7a24f6f375f6d762e6eebbdc93a829b9149167. --- tests/tests_spec.rb | 470 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 470 insertions(+) create mode 100644 tests/tests_spec.rb diff --git a/tests/tests_spec.rb b/tests/tests_spec.rb new file mode 100644 index 0000000..85f3750 --- /dev/null +++ b/tests/tests_spec.rb @@ -0,0 +1,470 @@ +# encoding: UTF-8 +require 'rosette_api' +require 'rspec' +require 'webmock/rspec' +require 'json' +WebMock.disable_net_connect!(allow_localhost: true) + +describe RosetteAPI do + + describe '.get_language' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/language.json')) + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/language'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'language'}.to_json, headers: {}) + end + it 'test language' do + params = DocumentParameters.new + params.content = 'Por favor Senorita, says the man.?' + response = RosetteAPI.new('0123456789').get_language(params) + expect(response).instance_of? Hash + end + + it 'badRequestFormat: the format of the request is invalid: multiple content sources' do + params = DocumentParameters.new + params.content = 'Por favor Senorita, says the man.?' + params.content_uri = 'Por favor Senorita, says the man.?' + expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(BadRequestFormatError) + end + + it 'badRequestFormat: the format of the request is invalid: no content provided;' do + params = DocumentParameters.new + expect { RosetteAPI.new('0123456789') + .get_language(params) } + .to raise_error(BadRequestFormatError) + end + end + + describe '.get_morphology_complete' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_complete.json')) + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/complete'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'morphology/complete'}.to_json, headers: {}) + end + it 'test morphology complete' do + params = DocumentParameters.new + params.content = 'The quick brown fox jumped over the lazy dog. Yes he did.' + response = RosetteAPI.new('0123456789').get_morphology_complete(params) + expect(response).instance_of? Hash + end + end + + describe '.get_compound_components' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_compound_components.json')) + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/compound-components'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'morphology/compound-components'}.to_json, headers: {}) + end + it 'test morphology compound components' do + params = DocumentParameters.new + params.content = 'Rechtsschutzversicherungsgesellschaften' + response = RosetteAPI.new('0123456789').get_compound_components(params) + expect(response).instance_of? Hash + end + end + + describe '.get_han_readings' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_han_readings.json')), encoding: 'utf-8' + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/han-readings'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'morphology/han-readings'}.to_json, headers: {}) + end + it 'test morphology han readings' do + params = DocumentParameters.new + params.content = '北京大学生物系主任办公室内部会议' + response = RosetteAPI.new('0123456789').get_han_readings(params) + expect(response).instance_of? Hash + end + end + + describe '.get_parts_of_speech' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_parts_of_speech.json')) + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/parts-of-speech'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'morphology/parts-of-speech'}.to_json, headers: {}) + end + it 'test morphology parts of speech' do + params = DocumentParameters.new + params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" + response = RosetteAPI.new('0123456789').get_parts_of_speech(params) + expect(response).instance_of? Hash + end + end + + describe '.get_lemmas' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_lemmas.json')) + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/lemmas'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'morphology/lemmas'}.to_json, headers: {}) + end + it 'test morphology lemmas' do + params = DocumentParameters.new + params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" + response = RosetteAPI.new('0123456789').get_lemmas(params) + expect(response).instance_of? Hash + end + end + + describe '.get_entities' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities.json')), encoding: 'utf-8' + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/entities'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'entities'}.to_json, headers: {}) + end + it 'test entities' do + params = DocumentParameters.new + params.content = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a' \ + ' cameo in Boston this… http://dlvr.it/BnsFfS' + response = RosetteAPI.new('0123456789').get_entities(params) + expect(response).instance_of? Hash + end + end + + describe '.get_entities_linked' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities_linked.json')) + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/entities/linked'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'entities/linked'}.to_json, headers: {}) + end + it 'test entities linked' do + params = DocumentParameters.new + params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including' \ + ' Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' + response = RosetteAPI.new('0123456789').get_entities_linked(params) + expect(response).instance_of? Hash + end + end + + describe '.get_categories' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/categories.json')) + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/categories'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'categories'}.to_json, headers: {}) + end + it 'test categories' do + params = DocumentParameters.new + params.content_uri = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' + response = RosetteAPI.new('0123456789').get_categories(params) + expect(response).instance_of? Hash + end + end + + describe '.get_relationships' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/relationships.json')) + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/relationships'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'relationships'}.to_json, headers: {}) + end + it 'test relationships' do + params = DocumentParameters.new + params.content = 'The Ghostbusters movie was filmed in Boston.' + response = RosetteAPI.new('0123456789').get_relationships(params) + expect(response).instance_of? Hash + end + end + + describe '.name_translation' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_translation.json')), encoding: 'utf-8' + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/name-translation'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'name-translation'}.to_json, headers: {}) + end + it 'test name translation' do + params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8'), 'eng') + params.target_script = 'Latn' + response = RosetteAPI.new('0123456789').name_translation(params) + expect(response).instance_of? Hash + end + end + + describe '.name_similarity' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_similarity.json')), encoding: 'utf-8' + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/name-similarity'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'name-similarity'}.to_json, headers: {}) + end + it 'test name similarity' do + params = NameSimilarityParameters.new('Michael Jackson', '迈克尔·杰克逊') + response = RosetteAPI.new('0123456789').name_similarity(params) + expect(response).instance_of? Hash + end + + it 'badRequestFormat: name2 option can only be an instance of a String or NameParameter' do + params = NameSimilarityParameters.new('Michael Jackson', 123) + expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(BadRequestError) + end + end + + describe '.get_tokens' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/tokens.json')), encoding: 'utf-8' + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/tokens'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'tokens'}.to_json, headers: {}) + end + it 'test tokens' do + params = DocumentParameters.new + params.content = '北京大学生物系主任办公室内部会议' + response = RosetteAPI.new('0123456789').get_tokens(params) + expect(response).instance_of? Hash + end + end + + describe '.get_sentences' do + request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/sentences.json')) + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:post, 'https://api.rosette.com/rest/v1/sentences'). + with(body: request_file, + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'sentences'}.to_json, headers: {}) + end + it 'test sentences' do + params = DocumentParameters.new + params.content = 'This land is your land. This land is my land\nFrom California to the New York island;\nFrom' \ + ' the wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was' \ + ' walking that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that' \ + ' golden valley:\nThis land was made for you and me.' + response = RosetteAPI.new('0123456789').get_sentences(params) + expect(response).instance_of? Hash + end + end + + describe '.info' do + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:get, 'https://api.rosette.com/rest/v1/info'). + with(headers: {'Accept' => '*/*', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'info'}.to_json, headers: {}) + end + it 'test info' do + response = RosetteAPI.new('0123456789').info + expect(response).instance_of? Hash + end + end + + describe '.ping' do + before do + stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). + with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", + headers: {'Accept' => 'application/json', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'Content-Type' => 'application/json', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) + stub_request(:get, 'https://api.rosette.com/rest/v1/ping'). + with(headers: {'Accept' => '*/*', + 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', + 'User-Agent' => 'Ruby', + 'X-Rosetteapi-Key' => '0123456789'}). + to_return(status: 200, body: {'test': 'ping'}.to_json, headers: {}) + end + it 'test ping' do + response = RosetteAPI.new('0123456789').ping + expect(response).instance_of? Hash + end + end +end From 265caae0dbf5afa84dc442c7aa575f42955ffa38 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 15:12:06 -0400 Subject: [PATCH 27/42] Removed test folder --- test/tests_spec.rb | 470 --------------------------------------------- 1 file changed, 470 deletions(-) delete mode 100644 test/tests_spec.rb diff --git a/test/tests_spec.rb b/test/tests_spec.rb deleted file mode 100644 index 85f3750..0000000 --- a/test/tests_spec.rb +++ /dev/null @@ -1,470 +0,0 @@ -# encoding: UTF-8 -require 'rosette_api' -require 'rspec' -require 'webmock/rspec' -require 'json' -WebMock.disable_net_connect!(allow_localhost: true) - -describe RosetteAPI do - - describe '.get_language' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/language.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/language'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'language'}.to_json, headers: {}) - end - it 'test language' do - params = DocumentParameters.new - params.content = 'Por favor Senorita, says the man.?' - response = RosetteAPI.new('0123456789').get_language(params) - expect(response).instance_of? Hash - end - - it 'badRequestFormat: the format of the request is invalid: multiple content sources' do - params = DocumentParameters.new - params.content = 'Por favor Senorita, says the man.?' - params.content_uri = 'Por favor Senorita, says the man.?' - expect { RosetteAPI.new('0123456789').get_language(params) }.to raise_error(BadRequestFormatError) - end - - it 'badRequestFormat: the format of the request is invalid: no content provided;' do - params = DocumentParameters.new - expect { RosetteAPI.new('0123456789') - .get_language(params) } - .to raise_error(BadRequestFormatError) - end - end - - describe '.get_morphology_complete' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_complete.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/complete'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/complete'}.to_json, headers: {}) - end - it 'test morphology complete' do - params = DocumentParameters.new - params.content = 'The quick brown fox jumped over the lazy dog. Yes he did.' - response = RosetteAPI.new('0123456789').get_morphology_complete(params) - expect(response).instance_of? Hash - end - end - - describe '.get_compound_components' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_compound_components.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/compound-components'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/compound-components'}.to_json, headers: {}) - end - it 'test morphology compound components' do - params = DocumentParameters.new - params.content = 'Rechtsschutzversicherungsgesellschaften' - response = RosetteAPI.new('0123456789').get_compound_components(params) - expect(response).instance_of? Hash - end - end - - describe '.get_han_readings' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_han_readings.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/han-readings'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/han-readings'}.to_json, headers: {}) - end - it 'test morphology han readings' do - params = DocumentParameters.new - params.content = '北京大学生物系主任办公室内部会议' - response = RosetteAPI.new('0123456789').get_han_readings(params) - expect(response).instance_of? Hash - end - end - - describe '.get_parts_of_speech' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_parts_of_speech.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/parts-of-speech'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/parts-of-speech'}.to_json, headers: {}) - end - it 'test morphology parts of speech' do - params = DocumentParameters.new - params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" - response = RosetteAPI.new('0123456789').get_parts_of_speech(params) - expect(response).instance_of? Hash - end - end - - describe '.get_lemmas' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_lemmas.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/lemmas'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'morphology/lemmas'}.to_json, headers: {}) - end - it 'test morphology lemmas' do - params = DocumentParameters.new - params.content = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" - response = RosetteAPI.new('0123456789').get_lemmas(params) - expect(response).instance_of? Hash - end - end - - describe '.get_entities' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/entities'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'entities'}.to_json, headers: {}) - end - it 'test entities' do - params = DocumentParameters.new - params.content = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a' \ - ' cameo in Boston this… http://dlvr.it/BnsFfS' - response = RosetteAPI.new('0123456789').get_entities(params) - expect(response).instance_of? Hash - end - end - - describe '.get_entities_linked' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities_linked.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/entities/linked'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'entities/linked'}.to_json, headers: {}) - end - it 'test entities linked' do - params = DocumentParameters.new - params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including' \ - ' Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' - response = RosetteAPI.new('0123456789').get_entities_linked(params) - expect(response).instance_of? Hash - end - end - - describe '.get_categories' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/categories.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/categories'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'categories'}.to_json, headers: {}) - end - it 'test categories' do - params = DocumentParameters.new - params.content_uri = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' - response = RosetteAPI.new('0123456789').get_categories(params) - expect(response).instance_of? Hash - end - end - - describe '.get_relationships' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/relationships.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/relationships'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'relationships'}.to_json, headers: {}) - end - it 'test relationships' do - params = DocumentParameters.new - params.content = 'The Ghostbusters movie was filmed in Boston.' - response = RosetteAPI.new('0123456789').get_relationships(params) - expect(response).instance_of? Hash - end - end - - describe '.name_translation' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_translation.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/name-translation'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'name-translation'}.to_json, headers: {}) - end - it 'test name translation' do - params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8'), 'eng') - params.target_script = 'Latn' - response = RosetteAPI.new('0123456789').name_translation(params) - expect(response).instance_of? Hash - end - end - - describe '.name_similarity' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_similarity.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/name-similarity'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'name-similarity'}.to_json, headers: {}) - end - it 'test name similarity' do - params = NameSimilarityParameters.new('Michael Jackson', '迈克尔·杰克逊') - response = RosetteAPI.new('0123456789').name_similarity(params) - expect(response).instance_of? Hash - end - - it 'badRequestFormat: name2 option can only be an instance of a String or NameParameter' do - params = NameSimilarityParameters.new('Michael Jackson', 123) - expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(BadRequestError) - end - end - - describe '.get_tokens' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/tokens.json')), encoding: 'utf-8' - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/tokens'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'tokens'}.to_json, headers: {}) - end - it 'test tokens' do - params = DocumentParameters.new - params.content = '北京大学生物系主任办公室内部会议' - response = RosetteAPI.new('0123456789').get_tokens(params) - expect(response).instance_of? Hash - end - end - - describe '.get_sentences' do - request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/sentences.json')) - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:post, 'https://api.rosette.com/rest/v1/sentences'). - with(body: request_file, - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'sentences'}.to_json, headers: {}) - end - it 'test sentences' do - params = DocumentParameters.new - params.content = 'This land is your land. This land is my land\nFrom California to the New York island;\nFrom' \ - ' the wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was' \ - ' walking that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that' \ - ' golden valley:\nThis land was made for you and me.' - response = RosetteAPI.new('0123456789').get_sentences(params) - expect(response).instance_of? Hash - end - end - - describe '.info' do - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:get, 'https://api.rosette.com/rest/v1/info'). - with(headers: {'Accept' => '*/*', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'info'}.to_json, headers: {}) - end - it 'test info' do - response = RosetteAPI.new('0123456789').info - expect(response).instance_of? Hash - end - end - - describe '.ping' do - before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) - stub_request(:get, 'https://api.rosette.com/rest/v1/ping'). - with(headers: {'Accept' => '*/*', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'test': 'ping'}.to_json, headers: {}) - end - it 'test ping' do - response = RosetteAPI.new('0123456789').ping - expect(response).instance_of? Hash - end - end -end From 2aa8b4bb17884d7b78ba8c1438b22950695fd082 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 15:17:16 -0400 Subject: [PATCH 28/42] Updated .travis.yml --- .travis.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index ae50524..c42a3b4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: ruby rvm: - - 2.0.0-p247 -script: rspec spec + - 2.3.0 +script: bundle exec rspec spec notifications: slack: From cde961857ee0f380adda5813efb626b24aa2be21 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 15:32:30 -0400 Subject: [PATCH 29/42] Updated README.md --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index cb4f0e3..3e9a690 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,13 @@ API Documentation See [documentation](http://rosette-api.github.io/ruby) +Testing +----------------- +Unit tests are based on RSpec. +1. Launch the docker image interactively, `sudo docker run --rm -it -e API_KEY=valid_api_key -v `pwd`:/source ruby-docker /bin/bash` +2. `cd tests` +3. `rspec tests_spec.rb` + Additional Information ---------------------- From 818a136737aa79e5277aa09d54b8804ad06a5fc9 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 15:32:30 -0400 Subject: [PATCH 30/42] Updated README.md --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index cb4f0e3..3e9a690 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,13 @@ API Documentation See [documentation](http://rosette-api.github.io/ruby) +Testing +----------------- +Unit tests are based on RSpec. +1. Launch the docker image interactively, `sudo docker run --rm -it -e API_KEY=valid_api_key -v `pwd`:/source ruby-docker /bin/bash` +2. `cd tests` +3. `rspec tests_spec.rb` + Additional Information ---------------------- From e91476781854f8f2b578b06adadd9bb6a0056bd4 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 15:55:47 -0400 Subject: [PATCH 31/42] Updated .travis.yml --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index c42a3b4..574671c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,7 @@ language: ruby rvm: - 2.3.0 -script: bundle exec rspec spec +script: rspec tests notifications: slack: From 507022844a8336de7062205fde5282f7018bf8f5 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 16:01:57 -0400 Subject: [PATCH 32/42] Added Travis CI build status to README.md --- README.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/README.md b/README.md index 3e9a690..6644b6a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -[![Build Status](https://travis-ci.org/rosette-api/ruby.svg?branch=master)](https://travis-ci.org/rosette-api/ruby) +[![Build Status](https://travis-ci.org/rosette-api/ruby.svg?branch=develop)](https://travis-ci.org/rosette-api/ruby) Ruby client binding for Rosette API ================================== @@ -19,13 +19,6 @@ API Documentation See [documentation](http://rosette-api.github.io/ruby) -Testing ------------------ -Unit tests are based on RSpec. -1. Launch the docker image interactively, `sudo docker run --rm -it -e API_KEY=valid_api_key -v `pwd`:/source ruby-docker /bin/bash` -2. `cd tests` -3. `rspec tests_spec.rb` - Additional Information ---------------------- From a315923e2a4dba16950726ff9aad77e0f0f92838 Mon Sep 17 00:00:00 2001 From: fiona Date: Mon, 2 May 2016 16:16:03 -0400 Subject: [PATCH 33/42] Updated run_ruby.sh to copy all examples from mounted volume --- examples/docker/run_ruby.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/docker/run_ruby.sh b/examples/docker/run_ruby.sh index 414204b..6616583 100644 --- a/examples/docker/run_ruby.sh +++ b/examples/docker/run_ruby.sh @@ -73,7 +73,7 @@ done validateURL #Copy the mounted content in /source to current WORKDIR -cp -r -n /source/. . +cp /source/examples/*.* . #Run the examples if [ ! -z ${API_KEY} ]; then From b095b7fdf027ea578b6d397f1e8d8f59cf2e47fa Mon Sep 17 00:00:00 2001 From: Chris Park Date: Tue, 3 May 2016 09:03:11 -0400 Subject: [PATCH 34/42] Renamed morphology examples to match slate expectations --- ...y_compound_components.rb => morphology_compound-components.rb} | 0 .../{morphology_han_readings.rb => morphology_han-readings.rb} | 0 ...orphology_parts_of_speech.rb => morphology_parts-of-speech.rb} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename examples/{morphology_compound_components.rb => morphology_compound-components.rb} (100%) rename examples/{morphology_han_readings.rb => morphology_han-readings.rb} (100%) rename examples/{morphology_parts_of_speech.rb => morphology_parts-of-speech.rb} (100%) diff --git a/examples/morphology_compound_components.rb b/examples/morphology_compound-components.rb similarity index 100% rename from examples/morphology_compound_components.rb rename to examples/morphology_compound-components.rb diff --git a/examples/morphology_han_readings.rb b/examples/morphology_han-readings.rb similarity index 100% rename from examples/morphology_han_readings.rb rename to examples/morphology_han-readings.rb diff --git a/examples/morphology_parts_of_speech.rb b/examples/morphology_parts-of-speech.rb similarity index 100% rename from examples/morphology_parts_of_speech.rb rename to examples/morphology_parts-of-speech.rb From 3ed6d70517003e17d6e02ce2dcd418fbc64e66e9 Mon Sep 17 00:00:00 2001 From: fiona Date: Tue, 3 May 2016 10:23:18 -0400 Subject: [PATCH 35/42] Bug fix when handling 429s --- lib/request_builder.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/request_builder.rb b/lib/request_builder.rb index 6e28377..ca64a01 100644 --- a/lib/request_builder.rb +++ b/lib/request_builder.rb @@ -6,7 +6,6 @@ # This class handles all Rosette API requests. class RequestBuilder - @retries = 5 # Alternate Rosette API URL attr_reader :alternate_url # Parameters to build the body of the request from @@ -18,6 +17,7 @@ def initialize(user_key, alternate_url, params = {}) #:notnew: @user_key = user_key @alternate_url = alternate_url @params = params + @retries = 5 end # Prepares a plain POST request for Rosette API. From d94bc55d0755c986b2ddba6afc75ea0c3dc468b0 Mon Sep 17 00:00:00 2001 From: fiona Date: Tue, 3 May 2016 11:43:49 -0400 Subject: [PATCH 36/42] Deprecated get_entities_linked --- docker/run_ruby.sh | 2 +- lib/rosette_api.rb | 18 ++++++++---------- rosette_api.gemspec | 2 +- 3 files changed, 10 insertions(+), 12 deletions(-) diff --git a/docker/run_ruby.sh b/docker/run_ruby.sh index eff2c77..ae74b12 100644 --- a/docker/run_ruby.sh +++ b/docker/run_ruby.sh @@ -87,7 +87,7 @@ cp -r -n /source/. . #Build rosette_api gem gem build rosette_api.gemspec -gem install ./rosette_api-1.0.1.gem +gem install ./rosette_api-1.0.2.gem #Run the examples if [ ! -z ${API_KEY} ]; then diff --git a/lib/rosette_api.rb b/lib/rosette_api.rb index 9c7ada6..4bbd16e 100644 --- a/lib/rosette_api.rb +++ b/lib/rosette_api.rb @@ -16,8 +16,6 @@ class RosetteAPI MORPHOLOGY_ENDPOINT = '/morphology' # Rosette API entities endpoint ENTITIES_ENDPOINT = '/entities' - # Rosette API entities/linked endpoint - ENTITIES_LINKED_ENDPOINT = '/entities/linked' # Rosette API categories endpoint CATEGORIES_ENDPOINT = '/categories' # Rosette API relationships endpoint @@ -173,14 +171,17 @@ def get_parts_of_speech(params) # ==== Attributes # # * +params+ - DocumentParameters helps to build the request body in RequestBuilder. + # * +resolve_entities+ - Enables entities to be linked in application endpoints. # # Returns each entity extracted from the input. - def get_entities(params) + def get_entities(params, resolve_entities = false) check_params params params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + ENTITIES_ENDPOINT, params) + endpoint = resolve_entities ? (ENTITIES_ENDPOINT + '/linked') : ENTITIES_ENDPOINT + + RequestBuilder.new(@user_key, @alternate_url + endpoint, params) .send_post_request end @@ -193,12 +194,9 @@ def get_entities(params) # Returns list of entities that have been linked to entities in the knowledge # base. def get_entities_linked(params) - check_params params - - params = params.load_params - - RequestBuilder.new(@user_key, @alternate_url + ENTITIES_LINKED_ENDPOINT, params) - .send_post_request + warn '[DEPRECATION] `get_entities_linked` is deprecated. Please use ' \ + '`get_entities` instead with `resolve_entities` param set to true.' + get_entities(params, true) end # Extracts Tier 1 contextual categories from the input. diff --git a/rosette_api.gemspec b/rosette_api.gemspec index 194907b..ad60c8c 100644 --- a/rosette_api.gemspec +++ b/rosette_api.gemspec @@ -8,7 +8,7 @@ Gem::Specification.new do |s| s.required_ruby_version = '>= 2.0.0' s.name = 'rosette_api' - s.version = '1.0.1' + s.version = '1.0.2' s.license = 'MIT' s.summary = 'Rosette API gem that supports multilingual text-analytics.' From 2b18826cf096b12923a7c58d795900fb8f3f8892 Mon Sep 17 00:00:00 2001 From: fiona Date: Tue, 3 May 2016 11:55:40 -0400 Subject: [PATCH 37/42] Docker file updated to generate gh-pages --- docker/run_ruby.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker/run_ruby.sh b/docker/run_ruby.sh index ae74b12..da8bcc4 100644 --- a/docker/run_ruby.sh +++ b/docker/run_ruby.sh @@ -117,7 +117,7 @@ if [ ! -z ${GIT_USERNAME} ] && [ ! -z ${VERSION} ]; then #generate gh-pages and set ouput dir to git repo (gh-pages branch) cd /ruby-dev/lib rdoc -o /doc - cp -r -n /doc/. /ruby + cp -r /doc/. /ruby cd /ruby git add . git commit -a -m "publish ruby apidocs ${VERSION}" From 1776fad847adb572a51b60735ced23ea09e53868 Mon Sep 17 00:00:00 2001 From: fiona Date: Tue, 3 May 2016 13:46:36 -0400 Subject: [PATCH 38/42] Updated linked_entities example --- docker/run_ruby.sh | 2 +- examples/entities_linked.rb | 2 +- lib/rosette_api.rb | 4 +++- rosette_api.gemspec | 2 +- tests/tests_spec.rb | 2 +- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docker/run_ruby.sh b/docker/run_ruby.sh index da8bcc4..acbe8f9 100644 --- a/docker/run_ruby.sh +++ b/docker/run_ruby.sh @@ -87,7 +87,7 @@ cp -r -n /source/. . #Build rosette_api gem gem build rosette_api.gemspec -gem install ./rosette_api-1.0.2.gem +gem install ./rosette_api-1.0.3.gem #Run the examples if [ ! -z ${API_KEY} ]; then diff --git a/examples/entities_linked.rb b/examples/entities_linked.rb index 2cb697f..7b32737 100644 --- a/examples/entities_linked.rb +++ b/examples/entities_linked.rb @@ -9,5 +9,5 @@ end params = DocumentParameters.new(content: 'Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.', genre: 'social-media') -response = rosette_api.get_entities_linked(params) +response = rosette_api.get_entities(params, true) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/lib/rosette_api.rb b/lib/rosette_api.rb index 4bbd16e..3e958f3 100644 --- a/lib/rosette_api.rb +++ b/lib/rosette_api.rb @@ -177,6 +177,8 @@ def get_parts_of_speech(params) def get_entities(params, resolve_entities = false) check_params params + raise BadRequestError.new('Expects boolean for resolve_entities') unless !!resolve_entities == resolve_entities + params = params.load_params endpoint = resolve_entities ? (ENTITIES_ENDPOINT + '/linked') : ENTITIES_ENDPOINT @@ -330,7 +332,7 @@ def ping # Checks that the right parameter type is being passed in. def check_params(params, message = 'Expects a DocumentParameters type as an argument', type = DocumentParameters) - raise BadRequest.new message unless params.is_a? type + raise BadRequestError.new message unless params.is_a? type end end diff --git a/rosette_api.gemspec b/rosette_api.gemspec index ad60c8c..d1e67cf 100644 --- a/rosette_api.gemspec +++ b/rosette_api.gemspec @@ -8,7 +8,7 @@ Gem::Specification.new do |s| s.required_ruby_version = '>= 2.0.0' s.name = 'rosette_api' - s.version = '1.0.2' + s.version = '1.0.3' s.license = 'MIT' s.summary = 'Rosette API gem that supports multilingual text-analytics.' diff --git a/tests/tests_spec.rb b/tests/tests_spec.rb index 85f3750..5f5b149 100644 --- a/tests/tests_spec.rb +++ b/tests/tests_spec.rb @@ -242,7 +242,7 @@ params = DocumentParameters.new params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including' \ ' Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' - response = RosetteAPI.new('0123456789').get_entities_linked(params) + response = RosetteAPI.new('0123456789').get_entities(params, true) expect(response).instance_of? Hash end end From c72d75ac88d5026ec0fbc3f5fd1145fdc91bf5b4 Mon Sep 17 00:00:00 2001 From: fiona Date: Tue, 3 May 2016 14:03:05 -0400 Subject: [PATCH 39/42] Added a few unit tests for type-checking --- tests/tests_spec.rb | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/tests_spec.rb b/tests/tests_spec.rb index 5f5b149..2b7d511 100644 --- a/tests/tests_spec.rb +++ b/tests/tests_spec.rb @@ -245,6 +245,13 @@ response = RosetteAPI.new('0123456789').get_entities(params, true) expect(response).instance_of? Hash end + + it 'test entities linked for resolve_entities is not a boolean' do + params = DocumentParameters.new + params.content = 'Last month director Paul Feig announced the movie will have an all-star female cast including' \ + ' Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' + expect { RosetteAPI.new('0123456789').get_entities(params, 'smth') }.to raise_error(BadRequestError) + end end describe '.get_categories' do @@ -329,6 +336,11 @@ response = RosetteAPI.new('0123456789').name_translation(params) expect(response).instance_of? Hash end + + it 'badRequest: Expects NameTransaltionParameters type as an argument' do + params = NameSimilarityParameters.new('Michael Jackson', '迈克尔·杰克逊') + expect { RosetteAPI.new('0123456789').name_translation(params) }.to raise_error(BadRequestError) + end end describe '.name_similarity' do @@ -357,10 +369,20 @@ expect(response).instance_of? Hash end + it 'badRequestFormat: name1 option can only be an instance of a String or NameParameter' do + params = NameSimilarityParameters.new(123, 'Michael Jackson') + expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(BadRequestError) + end + it 'badRequestFormat: name2 option can only be an instance of a String or NameParameter' do params = NameSimilarityParameters.new('Michael Jackson', 123) expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(BadRequestError) end + + it 'badRequest: Expects NameSimilarityParameters type as an argument' do + params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف'.encode('UTF-8'), 'eng') + expect { RosetteAPI.new('0123456789').name_similarity(params) }.to raise_error(BadRequestError) + end end describe '.get_tokens' do From 63400a619e739e63fcf84a4a34e6e531a2c6e142 Mon Sep 17 00:00:00 2001 From: fiona Date: Tue, 3 May 2016 14:25:08 -0400 Subject: [PATCH 40/42] Updated Dockerfile that runs examples against published source --- examples/docker/Dockerfile | 2 -- examples/docker/run_ruby.sh | 3 +++ rosette_api.gemspec | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/examples/docker/Dockerfile b/examples/docker/Dockerfile index 6c67ebb..192f63a 100644 --- a/examples/docker/Dockerfile +++ b/examples/docker/Dockerfile @@ -6,8 +6,6 @@ RUN apt-get -y update && apt-get install -y \ vim \ git -RUN gem install rosette_api - RUN mkdir /ruby WORKDIR /ruby COPY run_ruby.sh run_ruby.sh diff --git a/examples/docker/run_ruby.sh b/examples/docker/run_ruby.sh index 6616583..30f6c1f 100644 --- a/examples/docker/run_ruby.sh +++ b/examples/docker/run_ruby.sh @@ -72,6 +72,9 @@ done validateURL +#Intall rosette_api from RubyGems +gem install rosette_api + #Copy the mounted content in /source to current WORKDIR cp /source/examples/*.* . diff --git a/rosette_api.gemspec b/rosette_api.gemspec index d1e67cf..dc2298a 100644 --- a/rosette_api.gemspec +++ b/rosette_api.gemspec @@ -19,7 +19,7 @@ Gem::Specification.new do |s| s.authors = ['Basis Technology Corp'] s.email = %q{support@rosette.com} s.homepage = %q{https://developer.rosette.com/} - s.date = %q{2016-04-29} + s.date = %q{2016-05-03} all_files = `git ls-files -z`.split("\x0") s.files = all_files.grep(%r{^(bin|lib)/|^.rubocop.yml$}) From 028826c3da6c0bb375b2061aa72977d0b83d8f81 Mon Sep 17 00:00:00 2001 From: fiona Date: Wed, 4 May 2016 13:11:02 -0400 Subject: [PATCH 41/42] Updated examples to match needed format for slate --- examples/categories.rb | 3 ++- examples/entities.rb | 3 ++- examples/entities_linked.rb | 3 ++- examples/language.rb | 3 ++- examples/morphology_complete.rb | 3 ++- examples/morphology_compound-components.rb | 3 ++- examples/morphology_han-readings.rb | 3 ++- examples/morphology_lemmas.rb | 3 ++- examples/morphology_parts-of-speech.rb | 3 ++- examples/name_similarity.rb | 7 ++++--- examples/name_translation.rb | 3 ++- examples/relationships.rb | 3 ++- examples/sentences.rb | 5 +++-- examples/sentiment.rb | 4 ++-- examples/tokens.rb | 3 ++- 15 files changed, 33 insertions(+), 19 deletions(-) diff --git a/examples/categories.rb b/examples/categories.rb index 704a941..132bd4e 100644 --- a/examples/categories.rb +++ b/examples/categories.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content_uri: 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/') +categories_url_data = 'http://www.onlocationvacations.com/2015/03/05/the-new-ghostbusters-movie-begins-filming-in-boston-in-june/' +params = DocumentParameters.new(content_uri: categories_url_data) response = rosette_api.get_categories(params) puts JSON.pretty_generate(response) diff --git a/examples/entities.rb b/examples/entities.rb index 2d68ae2..ed7625b 100644 --- a/examples/entities.rb +++ b/examples/entities.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS') +entities_text_data = 'Bill Murray will appear in new Ghostbusters film: Dr. Peter Venkman was spotted filming a cameo in Boston this… http://dlvr.it/BnsFfS' +params = DocumentParameters.new(content: entities_text_data) response = rosette_api.get_entities(params) puts JSON.pretty_generate(response) diff --git a/examples/entities_linked.rb b/examples/entities_linked.rb index 7b32737..cb96868 100644 --- a/examples/entities_linked.rb +++ b/examples/entities_linked.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: 'Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.', genre: 'social-media') +entities_linked_text_data = 'Last month director Paul Feig announced the movie will have an all-star female cast including Kristen Wiig, Melissa McCarthy, Leslie Jones and Kate McKinnon.' +params = DocumentParameters.new(content: entities_linked_text_data, genre: 'social-media') response = rosette_api.get_entities(params, true) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/language.rb b/examples/language.rb index 29612ab..8175b2a 100644 --- a/examples/language.rb +++ b/examples/language.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: 'Por favor Señorita, says the man.?') +language_data = 'Por favor Señorita, says the man.?' +params = DocumentParameters.new(content: language_data) response = rosette_api.get_language(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_complete.rb b/examples/morphology_complete.rb index 3803e60..0842fbd 100644 --- a/examples/morphology_complete.rb +++ b/examples/morphology_complete.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: 'The quick brown fox jumped over the lazy dog. Yes he did.') +morphology_complete_data = 'The quick brown fox jumped over the lazy dog. Yes he did.' +params = DocumentParameters.new(content: morphology_complete_data) response = rosette_api.get_morphology_complete(params) puts JSON.pretty_generate(response) diff --git a/examples/morphology_compound-components.rb b/examples/morphology_compound-components.rb index 622298f..75d1ff0 100644 --- a/examples/morphology_compound-components.rb +++ b/examples/morphology_compound-components.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: 'Rechtsschutzversicherungsgesellschaften') +morphology_compound_components_data = 'Rechtsschutzversicherungsgesellschaften' +params = DocumentParameters.new(content: morphology_compound_components_data) response = rosette_api.get_compound_components(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_han-readings.rb b/examples/morphology_han-readings.rb index 226535c..b3d0685 100644 --- a/examples/morphology_han-readings.rb +++ b/examples/morphology_han-readings.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: '北京大学生物系主任办公室内部会议') +morphology_han_readings_data = '北京大学生物系主任办公室内部会议' +params = DocumentParameters.new(content: morphology_han_readings_data) response = rosette_api.get_han_readings(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_lemmas.rb b/examples/morphology_lemmas.rb index 51404ce..ce72907 100644 --- a/examples/morphology_lemmas.rb +++ b/examples/morphology_lemmas.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: "The fact is that the geese just went back to get a rest and I'm not banking on their return soon") +morphology_lemmas_data = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" +params = DocumentParameters.new(content: morphology_lemmas_data) response = rosette_api.get_lemmas(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/morphology_parts-of-speech.rb b/examples/morphology_parts-of-speech.rb index 464c29b..ea65436 100644 --- a/examples/morphology_parts-of-speech.rb +++ b/examples/morphology_parts-of-speech.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: "The fact is that the geese just went back to get a rest and I'm not banking on their return soon") +morphology_parts_of_speech_data = "The fact is that the geese just went back to get a rest and I'm not banking on their return soon" +params = DocumentParameters.new(content: morphology_parts_of_speech_data) response = rosette_api.get_parts_of_speech(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_similarity.rb b/examples/name_similarity.rb index 2197a03..b8155e0 100644 --- a/examples/name_similarity.rb +++ b/examples/name_similarity.rb @@ -8,8 +8,9 @@ rosette_api = RosetteAPI.new(api_key, url) end - -name1 = NameParameter.new('Michael Jackson', entity_type: 'PERSON', language:'eng') -params = NameSimilarityParameters.new(name1, '迈克尔·杰克逊') +matched_name_data1 = 'Michael Jackson' +matched_name_data2 = '迈克尔·杰克逊' +name1 = NameParameter.new(matched_name_data1, entity_type: 'PERSON', language:'eng') +params = NameSimilarityParameters.new(name1, matched_name_data2) response = rosette_api.name_similarity(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/name_translation.rb b/examples/name_translation.rb index b88922f..efc24e3 100644 --- a/examples/name_translation.rb +++ b/examples/name_translation.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = NameTranslationParameters.new('معمر محمد أبو منيار القذاف', 'eng', target_script: 'Latn') +translated_name_data = 'معمر محمد أبو منيار القذاف' +params = NameTranslationParameters.new(translated_name_data, 'eng', target_script: 'Latn') response = rosette_api.name_translation(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/relationships.rb b/examples/relationships.rb index 59bf35f..63e98b2 100644 --- a/examples/relationships.rb +++ b/examples/relationships.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: 'The Ghostbusters movie was filmed in Boston.') +relationships_text_data = 'The Ghostbusters movie was filmed in Boston.' +params = DocumentParameters.new(content: relationships_text_data) response = rosette_api.get_relationships(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/sentences.rb b/examples/sentences.rb index 4a5245b..a840bbd 100644 --- a/examples/sentences.rb +++ b/examples/sentences.rb @@ -8,10 +8,11 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new -params.content = 'This land is your land. This land is my land\nFrom California to the New York island;\nFrom the' \ +sentences_data = 'This land is your land. This land is my land\nFrom California to the New York island;\nFrom the' \ ' wood forest to the Gulf Stream waters\n\nThis land was made for you and Me.\n\nAs I was walking' \ ' that ribbon of highway,\nI saw above me that endless skyway:\nI saw below me that' \ ' golden valley:\nThis land was made for you and me.' +params = DocumentParameters.new +params.content = sentences_data response = rosette_api.get_sentences(params) puts JSON.pretty_generate(response) \ No newline at end of file diff --git a/examples/sentiment.rb b/examples/sentiment.rb index 6155ea2..8ddb2fd 100644 --- a/examples/sentiment.rb +++ b/examples/sentiment.rb @@ -11,12 +11,12 @@ file = Tempfile.new(%w(foo .html)) -sentiment_text_data = 'New Ghostbusters Film

Original Ghostbuster Dan ' \ +sentiment_file_data = 'New Ghostbusters Film

Original Ghostbuster Dan ' \ 'Aykroyd, who also co-wrote the 1984 Ghostbusters film, couldn’t be more pleased with the new ' \ 'all-female Ghostbusters cast, telling The Hollywood Reporter, The Aykroyd family is delighted ' \ 'by this inheritance of the Ghostbusters torch by these most magnificent women in comedy ' \ '.

' -file.write(sentiment_text_data) +file.write(sentiment_file_data) file.close params = DocumentParameters.new(file_path: file.path, language: 'eng') response = rosette_api.get_sentiment(params) diff --git a/examples/tokens.rb b/examples/tokens.rb index 8be177e..e35194e 100644 --- a/examples/tokens.rb +++ b/examples/tokens.rb @@ -8,6 +8,7 @@ rosette_api = RosetteAPI.new(api_key, url) end -params = DocumentParameters.new(content: '北京大学生物系主任办公室内部会议') +tokens_data = '北京大学生物系主任办公室内部会议' +params = DocumentParameters.new(content: tokens_data) response = rosette_api.get_tokens(params) puts JSON.pretty_generate(response) \ No newline at end of file From 43477ef7ef587363d27ea7ba46af7dea6743f382 Mon Sep 17 00:00:00 2001 From: SamHausmann Date: Wed, 11 May 2016 11:38:18 -0400 Subject: [PATCH 42/42] removed check version and added new headers to be sent to API to transmit binding data --- lib/request_builder.rb | 12 ++- lib/rosette_api.rb | 50 ++++------- tests/tests_spec.rb | 187 ++++++++++------------------------------- 3 files changed, 71 insertions(+), 178 deletions(-) diff --git a/lib/request_builder.rb b/lib/request_builder.rb index ca64a01..d254e98 100644 --- a/lib/request_builder.rb +++ b/lib/request_builder.rb @@ -1,3 +1,4 @@ +# encoding: UTF-8 require 'net/http' require 'net/https' require 'json' @@ -12,12 +13,15 @@ class RequestBuilder attr_accessor :params # Rosette API key attr_accessor :user_key + # Rosette API binding version + attr_accessor :binding_version - def initialize(user_key, alternate_url, params = {}) #:notnew: + def initialize(user_key, alternate_url, params = {}, binding_version) #:notnew: @user_key = user_key @alternate_url = alternate_url @params = params @retries = 5 + @binding_version = binding_version end # Prepares a plain POST request for Rosette API. @@ -40,6 +44,8 @@ def prepare_plain_request(params) request['X-RosetteAPI-Key'] = @user_key request['Content-Type'] = 'application/json' request['Accept'] = 'application/json' + request['X-RosetteAPI-Binding'] = 'ruby' + request['X-RosetteAPI-Binding-Version'] = @binding_version request.body = params.to_json [http, request] @@ -84,6 +90,8 @@ def prepare_multipart_request(params) request = Net::HTTP::Post.new uri.request_uri request.add_field 'Content-Type', "multipart/form-data; boundary=#{boundary}" request.add_field 'X-RosetteAPI-Key', @user_key + request.add_field 'X-RosetteAPI-Binding', 'ruby' + request.add_field 'X-RosetteAPI-Binding-Version', @binding_version request.body = post_body.join [http, request] @@ -107,8 +115,6 @@ def send_get_request # # Returns JSON response or raises RosetteAPIError if encountered. def send_post_request - params = (@alternate_url.to_s.include? '/info?clientVersion=') ? '{"body": "version check"}' : @params - if !params['filePath'].nil? http, request = self.prepare_multipart_request params else diff --git a/lib/rosette_api.rb b/lib/rosette_api.rb index 3e958f3..25f852a 100644 --- a/lib/rosette_api.rb +++ b/lib/rosette_api.rb @@ -32,8 +32,6 @@ class RosetteAPI SENTENCES_ENDPOINT = '/sentences' # Rosette API info endpoint INFO = '/info' - # Rosette API version check endpoint - VERSION_CHECK = '/info?clientVersion=' + BINDING_VERSION # Rosette API ping endpoint PING = '/ping' @@ -49,20 +47,6 @@ def initialize(user_key, alternate_url = 'https://api.rosette.com/rest/v1') #:no if @alternate_url.to_s.end_with?('/') @alternate_url = alternate_url.to_s.slice(0..-2) end - - self.check_version_compatibility - end - - # Checks binding version compatibility against the Rosette API server. - def check_version_compatibility - response = RequestBuilder.new(@user_key, @alternate_url + VERSION_CHECK) - .send_post_request - - unless response['versionChecked'] - puts JSON.pretty_generate(response) - - exit - end end # Identifies in which language(s) the input is written. @@ -77,7 +61,7 @@ def get_language(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + LANGUAGE_ENDPOINT, params) + RequestBuilder.new(@user_key, @alternate_url + LANGUAGE_ENDPOINT, params, BINDING_VERSION) .send_post_request end @@ -95,7 +79,7 @@ def get_morphology_complete(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/complete', params) + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/complete', params, BINDING_VERSION) .send_post_request end @@ -112,7 +96,7 @@ def get_compound_components(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/compound-components', params) + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/compound-components', params, BINDING_VERSION) .send_post_request end @@ -129,7 +113,7 @@ def get_han_readings(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/han-readings', params) + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/han-readings', params, BINDING_VERSION) .send_post_request end @@ -145,7 +129,7 @@ def get_lemmas(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/lemmas', params) + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/lemmas', params, BINDING_VERSION) .send_post_request end @@ -162,7 +146,7 @@ def get_parts_of_speech(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/parts-of-speech', params) + RequestBuilder.new(@user_key, @alternate_url + MORPHOLOGY_ENDPOINT + '/parts-of-speech', params, BINDING_VERSION) .send_post_request end @@ -183,7 +167,7 @@ def get_entities(params, resolve_entities = false) endpoint = resolve_entities ? (ENTITIES_ENDPOINT + '/linked') : ENTITIES_ENDPOINT - RequestBuilder.new(@user_key, @alternate_url + endpoint, params) + RequestBuilder.new(@user_key, @alternate_url + endpoint, params, BINDING_VERSION) .send_post_request end @@ -213,7 +197,7 @@ def get_categories(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + CATEGORIES_ENDPOINT, params) + RequestBuilder.new(@user_key, @alternate_url + CATEGORIES_ENDPOINT, params, BINDING_VERSION) .send_post_request end @@ -229,7 +213,7 @@ def get_relationships(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + RELATIONSHIPS_ENDPOINT, params) + RequestBuilder.new(@user_key, @alternate_url + RELATIONSHIPS_ENDPOINT, params, BINDING_VERSION) .send_post_request end @@ -245,7 +229,7 @@ def get_sentiment(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + SENTIMENT_ENDPOINT, params) + RequestBuilder.new(@user_key, @alternate_url + SENTIMENT_ENDPOINT, params, BINDING_VERSION) .send_post_request end @@ -261,7 +245,7 @@ def name_translation(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + NAME_TRANSLATION_ENDPOINT, params) + RequestBuilder.new(@user_key, @alternate_url + NAME_TRANSLATION_ENDPOINT, params, BINDING_VERSION) .send_post_request end @@ -278,7 +262,7 @@ def name_similarity(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + NAME_SIMILARITY_ENDPOINT, params) + RequestBuilder.new(@user_key, @alternate_url + NAME_SIMILARITY_ENDPOINT, params, BINDING_VERSION) .send_post_request end @@ -294,7 +278,7 @@ def get_tokens(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + TOKENS_ENDPOINT, params) + RequestBuilder.new(@user_key, @alternate_url + TOKENS_ENDPOINT, params, BINDING_VERSION) .send_post_request end @@ -310,21 +294,21 @@ def get_sentences(params) params = params.load_params - RequestBuilder.new(@user_key, @alternate_url + SENTENCES_ENDPOINT, params) + RequestBuilder.new(@user_key, @alternate_url + SENTENCES_ENDPOINT, params, BINDING_VERSION) .send_post_request end - # Gets information about the Rosette API, returns name, version, build number + # Gets information about the Rosette API, returns name, build number # and build time. def info - RequestBuilder.new(@user_key, @alternate_url + INFO) + RequestBuilder.new(@user_key, @alternate_url + INFO, BINDING_VERSION) .send_get_request end # Pings the Rosette API for a response indicting that the service is # available. def ping - RequestBuilder.new(@user_key, @alternate_url + PING) + RequestBuilder.new(@user_key, @alternate_url + PING, BINDING_VERSION) .send_get_request end diff --git a/tests/tests_spec.rb b/tests/tests_spec.rb index 2b7d511..b39c1c8 100644 --- a/tests/tests_spec.rb +++ b/tests/tests_spec.rb @@ -10,21 +10,15 @@ describe '.get_language' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/language.json')) before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/language'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'language'}.to_json, headers: {}) end it 'test language' do @@ -47,26 +41,21 @@ .get_language(params) } .to raise_error(BadRequestFormatError) end + end describe '.get_morphology_complete' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_complete.json')) before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/complete'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'morphology/complete'}.to_json, headers: {}) end it 'test morphology complete' do @@ -80,21 +69,15 @@ describe '.get_compound_components' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_compound_components.json')) before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/compound-components'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'morphology/compound-components'}.to_json, headers: {}) end it 'test morphology compound components' do @@ -108,21 +91,15 @@ describe '.get_han_readings' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_han_readings.json')), encoding: 'utf-8' before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/han-readings'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'morphology/han-readings'}.to_json, headers: {}) end it 'test morphology han readings' do @@ -136,21 +113,15 @@ describe '.get_parts_of_speech' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_parts_of_speech.json')) before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/parts-of-speech'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'morphology/parts-of-speech'}.to_json, headers: {}) end it 'test morphology parts of speech' do @@ -164,21 +135,15 @@ describe '.get_lemmas' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/morphology_lemmas.json')) before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/morphology/lemmas'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'morphology/lemmas'}.to_json, headers: {}) end it 'test morphology lemmas' do @@ -192,21 +157,15 @@ describe '.get_entities' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities.json')), encoding: 'utf-8' before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/entities'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'entities'}.to_json, headers: {}) end it 'test entities' do @@ -221,21 +180,15 @@ describe '.get_entities_linked' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/entities_linked.json')) before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/entities/linked'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'entities/linked'}.to_json, headers: {}) end it 'test entities linked' do @@ -257,21 +210,15 @@ describe '.get_categories' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/categories.json')) before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/categories'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'categories'}.to_json, headers: {}) end it 'test categories' do @@ -285,21 +232,15 @@ describe '.get_relationships' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/relationships.json')) before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/relationships'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'relationships'}.to_json, headers: {}) end it 'test relationships' do @@ -313,21 +254,15 @@ describe '.name_translation' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_translation.json')), encoding: 'utf-8' before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/name-translation'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'name-translation'}.to_json, headers: {}) end it 'test name translation' do @@ -346,21 +281,15 @@ describe '.name_similarity' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/name_similarity.json')), encoding: 'utf-8' before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/name-similarity'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'name-similarity'}.to_json, headers: {}) end it 'test name similarity' do @@ -388,21 +317,15 @@ describe '.get_tokens' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/tokens.json')), encoding: 'utf-8' before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/tokens'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'tokens'}.to_json, headers: {}) end it 'test tokens' do @@ -416,21 +339,15 @@ describe '.get_sentences' do request_file = File.read File.expand_path(File.join(File.dirname(__FILE__), '../mock-data/request/sentences.json')) before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:post, 'https://api.rosette.com/rest/v1/sentences'). with(body: request_file, headers: {'Accept' => 'application/json', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Content-Type' => 'application/json', 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). + 'X-Rosetteapi-Key' => '0123456789', + 'X-Rosetteapi-Binding' => 'ruby', + 'X-Rosetteapi-Binding-Version' => '1.0.2'}). to_return(status: 200, body: {'test': 'sentences'}.to_json, headers: {}) end it 'test sentences' do @@ -446,14 +363,6 @@ describe '.info' do before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:get, 'https://api.rosette.com/rest/v1/info'). with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', @@ -469,14 +378,6 @@ describe '.ping' do before do - stub_request(:post, 'https://api.rosette.com/rest/v1/info?clientVersion=1.0.2'). - with(body: "\"{\\\"body\\\": \\\"version check\\\"}\"", - headers: {'Accept' => 'application/json', - 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', - 'Content-Type' => 'application/json', - 'User-Agent' => 'Ruby', - 'X-Rosetteapi-Key' => '0123456789'}). - to_return(status: 200, body: {'versionChecked': true}.to_json, headers: {}) stub_request(:get, 'https://api.rosette.com/rest/v1/ping'). with(headers: {'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', @@ -489,4 +390,6 @@ expect(response).instance_of? Hash end end + + end