How to pass in values and headers via Ruby basic authentication? - ruby

I'm trying to pass in certain values and headers via Ruby but not sure how to do it. What I have so far:
uri = URI.parse('http://jira.test.local/rest/zapi/latest/execution')
req = Net::HTTP::Get.new(uri)
req.basic_auth 'userid', 'password'
res = Net::HTTP.start(uri.hostname, uri.port) {|http| http.request(req)}
puts res.body
values = "{\n \"issueId\": 32640,\n \"versionId\": \"11163\",\n \"cycleId\": \"5\",\n \"projectId\": 10460\n,\n \"status\": \"1\"}"
headers = {:content_type => "application/json"}
Net::HTTP.start(uri.hostname, uri.port) do | http |
response = http.post(req, values)
puts response.body
end
I'm getting this error right now:
{"status":{"1":{"id":1,"color":"#75B000","description":"Test was executed and passed successfully.","name":"PASS"},"2":{"id":2,"color":"#CC3300","description":"Test was executed and failed.","name":"FAIL"},"3":{"id":3,"color":"#F2B000","description":"Test execution is a work-in-progress.","name":"WIP"},"4":{"id":4,"color":"#6693B0","description":"The test execution of this test was blocked for some reason.","name":"BLOCKED"},"-1":{"id":-1,"color":"#A0A0A0","description":"The test has not yet been executed.","name":"UNEXECUTED"}},"executions":[],"currentlySelectedExecutionId":""}
undefined method `empty?' for #<Net::HTTP::Get GET> (NoMethodError)
/Users/fyousuf/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/net/http/generic_request.rb:27:in `initialize'
/Users/fyousuf/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/net/http/request.rb:14:in `initialize'
/Users/fyousuf/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/net/http.rb:1390:in `new'
/Users/fyousuf/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/net/http.rb:1390:in `send_entity'
/Users/fyousuf/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/net/http.rb:1179:in `post'
./features/step_definitions/zapi_farooq.rb:32:in `block (2 levels) in <top (required)>'
/Users/fyousuf/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/net/http.rb:852:in `start'
/Users/fyousuf/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/net/http.rb:582:in `start'
./features/step_definitions/zapi_farooq.rb:31:in `/^I test zapi update$/'
features/zapi_farooq.feature:4:in `* I test zapi update'
The first line of the output is good, it's giving me the proper outpul from the res.body, but after that is the error.
Summary: I want to go to the uri, authenticate with creds and post with the values provided and with the proper headers (all using Ruby).
I'm trying to create a new execution as per this API: http://docs.getzephyr.apiary.io/#executionresourceapis (Create a new Execution)

Playing around I got it to work with:
values = "{\n \"status\": 2\n}"
headers = {:content_type => "application/json"}
response = RestClient::Resource.new 'http://jira.test.local/rest/zapi/latest/execution/343/execute', 'username', 'password'
response.put values, headers
puts response
puts response.body
Gives output of:
http://jira.test.local/rest/zapi/latest/execution/343/execute
<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body></body></html>
Also it changes the value of the issue in Jira (intended goal).
I just used RestClient b/c the original docs (http://docs.getzephyr.apiary.io/#executionresourceapis) were using it and got some help here too: https://github.com/rest-client/rest-client

Related

Ruby: hitting read_timeout even when changed

From my Ruby code il make a call to a API.
On the testsystem with few data it works without a flaw.
On the Productive System it works too, but only if not much data is transmitted. If its too much data il get:
/usr/lib/ruby/2.3.0/net/protocol.rb:158:in rbuf_fill': Net::ReadTimeout (Net::ReadTimeout)
from /usr/lib/ruby/2.3.0/net/protocol.rb:136:inreaduntil'
from /usr/lib/ruby/2.3.0/net/protocol.rb:146:in readline'
from /usr/lib/ruby/2.3.0/net/http/response.rb:40:inread_status_line'
from /usr/lib/ruby/2.3.0/net/http/response.rb:29:in read_new'
from /usr/lib/ruby/2.3.0/net/http.rb:1437:inblock in transport_request'
from /usr/lib/ruby/2.3.0/net/http.rb:1434:in catch'
from /usr/lib/ruby/2.3.0/net/http.rb:1434:intransport_request'
from /usr/lib/ruby/2.3.0/net/http.rb:1407:in `request'
the relevant part in the code seems to be:
http = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => OpenSSL::SSL::VERIFY_NONE, :read_timeout => #timeout)
i bumped the #timeout to 900 and id didnt work eater.
Any ideas how i can get that to work or how i can debug that issue?

How to get around HTTParty invalid code lengths set (Zlib::DataError)?

When sending an HTTParty.get() request to a URL that redirects to another (one, or possibly more) URL(s), I get this error:
Zlib::DataError:
invalid code lengths set
# ./file/file_name.rb:63:in `block (3 levels) in <top (required)>'
How do I get around this, and why is it happening?
Set the Accept-Encoding param in the headers option to blank:
resp = HTTParty.get(article.old_url, :verify => false, :headers => {'Accept-Encoding' => ''})
HTTParty was having errors decompressing the response (specifically gzip in my case), possibly because something strange was happening with the received Content-Type header as a result of the redirect(s). Setting the Accept-Encoding header to blank returned something that HTTParty knew how to parse.

How to use Icescrum with Dashing (widget)?

I am trying to create a widget on Dashing that will extract data from Icescrum and update a specific widget.
The thing is I found info on how to program jira, so i've been trying to mess around with it to make it work with icescrum, but with no luck.
I tried this one:
require "uri"
require "net/http"
require "json"
SCHEDULER.every '2s', :first_in => 0 do |job|
uri = URI.parse("http://website.ca:8080/icescrum")
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Get.new("uri.request_uri")
req.basic_auth username, password
response = http.request(req)
issuesinProgress = JSON.parse(response.body)["total"]
send_event('synergy', value: issuesinProgress)
end
but I got this error:
scheduler caught exception:
undefined local variable or method `username' for main:Object
/home/administrator/dashboard/jobs/sample.rb:27:in `block in <top (required)>'
/var/lib/gems/1.9.1/gems/rufus-scheduler-2.0.24/lib/rufus/sc/jobs.rb:230:in `call'
/var/lib/gems/1.9.1/gems/rufus-scheduler-2.0.24/lib/rufus/sc/jobs.rb:230:in `trigger_block'
/var/lib/gems/1.9.1/gems/rufus-scheduler-2.0.24/lib/rufus/sc/jobs.rb:204:in `block in trigger'
/var/lib/gems/1.9.1/gems/rufus-scheduler-2.0.24/lib/rufus/sc/scheduler.rb:430:in `call'
/var/lib/gems/1.9.1/gems/rufus-scheduler-2.0.24/lib/rufus/sc/scheduler.rb:430:in `block in trigger_job'
Your code has a line:
req.basic_auth username, password
It's expecting two variables, "username" and "password", but neither look to be defined in your code, here. If they aren't defined you'll get an error that looks an awful lot like what you're getting.
So finally I just used a cURL function to get the information. I'll leave it here if anyone else needs it. It also sends the results to an xml file (if you don't want that then just remove the last part)
.rb file:
%x{curl -v -H "Content-Type: application/xml" -X POST --data "#filename.xml" -u username:password http://website.ca:8080/icescrum/ --output result.xml}
Remember to change these dummy names with your links:
filename.xml
username
password
website.ca:8080/icescrum/
result.xml
a complete set up of the widget is also available here :
https://github.com/Flash-Dash/Icescrum-widget

Savon - Program crash at "Error" Response

I made a simple SOAP-Request using Savon.
require 'savon'
client = Savon.client(:wsdl => 'https://url?wsdl', :ssl_verify_mode => :none,
wsse_auth: ["username", "password"],pretty_print_xml: true)
trackingnumber = 'anyNumber'
response = client.call(:shipment_status) do
message(Id: trackingnumber)
end
puts response
The problem is, if I get a "Error-Response", for instance if the trackingnumber don`t exists, then my program is crashing. But I dont want the program to crash, I want to keep the response. Here is the error:
c:/Ruby200/lib/ruby/gems/2.0.0/gems/savon-2.3.2/lib/savon/response.rb:85:in `raise_soap_and_http_errors!': (soap:Server) Fault occurred while processing. (Savon::SOAPFault)
from c:/Ruby200/lib/ruby/gems/2.0.0/gems/savon-2.3.2/lib/savon/response.rb:14:in `initialize'
from c:/Ruby200/lib/ruby/gems/2.0.0/gems/savon-2.3.2/lib/savon/operation.rb:64:in `new'
from c:/Ruby200/lib/ruby/gems/2.0.0/gems/savon-2.3.2/lib/savon/operation.rb:64:in `create_response'
from c:/Ruby200/lib/ruby/gems/2.0.0/gems/savon-2.3.2/lib/savon/operation.rb:55:in `call'
from c:/Ruby200/lib/ruby/gems/2.0.0/gems/savon-2.3.2/lib/savon/client.rb:36:in `call'
Is there a solution for this problem?
I think your syntax is off. Do you use Savon 2.x?
You should guard the call with an Exception handler.
require 'savon'
client = Savon.client(
:wsdl => 'https://url?wsdl',
:ssl_verify_mode => :none,
wsse_auth: ["username", "password"],
:raise_errors => true, # false if you don't want to see exceptions
pretty_print_xml: true)
trackingnumber = 'anyNumber'
begin
response = client.call(
:shipment_status,
:messageId => {:trackingnumber => trackingnumber}
)
rescue Savon::Error => soap_fault
print "Error: #{soap_fault}\n"
end
puts response
You can also set the parameter :raise_errors to false when creating your client. then you have to handle the return values accordingly.

How do I open local image file, encode it, and post via URI? (posting via Tumblr API)

I'm trying to read local image file, properly encode it and post to Tumbrl. According to the Tumblr API I can pass a parameter data which is Array (URL-encoded binary contents) Limit: 5 MB
I've tested my code with http://api.tumblr.com/v2/blog/#{BLOG}/info request. It is working. But I can't post a photo. Here is my code:
require 'oauth'
require 'oauth/consumer'
require 'open-uri'
require 'active_support'
CONSUMER = 'foo'
SECRET = 'foo'
TOKEN = 'foo'
TOKEN_SECRET = 'foo'
BLOG = 'foo'
consumer=OAuth::Consumer.new(CONSUMER, SECRET, {:site=>"http://tumblr.com"})
access_token = OAuth::AccessToken.new(consumer, TOKEN, TOKEN_SECRET)
# Here I tried one of two lines:
# data = Base64.encode64(IO.binread('./resized')) #first try
data = URI::encode(IO.binread('./resized')) #second try
# response = access_token.get "http://api.tumblr.com/v2/blog/#{BLOG}/info?api_key=#{CONSUMER}"
# puts response
response=access_token.post "http://api.tumblr.com/v2/blog/#{BLOG}/post?api_key=#{CONSUMER}&type=photo&data=#{data}&link=http://ya.ru&"
puts response
1st try:
% ruby ./w_oauth.rb
/usr/lib/ruby/1.9.1/uri/common.rb:176:in `split': bad URI(is not URI?): http://api.tumblr.com/v2/blog/foo/post?api_key=foo&type=photo&data=/9j/4AAQSkZJRgABAQEASABIAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4w (URI::InvalidURIError)
ICh1c2luZyBJSkcgSlBFRyB2NjIpLCBxdWFsaXR5ID0gODAK/9sAQwAGBAUG
BQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxobIxwWFiAsICMm
(!!!long piece of image data skipped!!!)
FI/16HfTbyHPWurqdE+TGH4wx2js5SKQb+6b4bIj3aurqCrEtcXrf/4yf/dS
DLet/wCzEB6sa6uoomxJN2eaQj5mkYuerQj611dQM7Fx/wDLF/8AbXV1dTA/
/9k=
&link=http://ya.ru&
from /usr/lib/ruby/1.9.1/uri/common.rb:211:in `parse'
from /usr/lib/ruby/1.9.1/uri/common.rb:747:in `parse'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/tokens/access_token.rb:7:in `request'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/tokens/access_token.rb:47:in `post'
from ./w_oauth.rb:23:in `<main>'
2nd try:
% ruby ./w_oauth.rb
/var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/helper.rb:14:in `force_encoding': can't modify frozen String (RuntimeError)
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/helper.rb:14:in `rescue in escape'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/helper.rb:12:in `escape'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/helper.rb:43:in `block (2 levels) in normalize'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/helper.rb:42:in `collect'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/helper.rb:42:in `block in normalize'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/helper.rb:37:in `map'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/helper.rb:37:in `normalize'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/request_proxy/base.rb:98:in `normalized_parameters'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/request_proxy/base.rb:113:in `signature_base_string'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/signature/base.rb:77:in `signature_base_string'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/signature/hmac/base.rb:12:in `digest'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/signature/base.rb:65:in `signature'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/signature.rb:23:in `sign'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/client/helper.rb:45:in `signature'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/client/helper.rb:75:in `header'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/client/net_http.rb:91:in `set_oauth_header'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/client/net_http.rb:30:in `oauth!'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/consumer.rb:224:in `sign!'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/consumer.rb:188:in `create_signed_request'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/consumer.rb:159:in `request'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/tokens/consumer_token.rb:25:in `request'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/tokens/access_token.rb:12:in `request'
from /var/lib/gems/1.9.1/gems/oauth-0.4.6/lib/oauth/tokens/access_token.rb:47:in `post'
from ./w_oauth.rb:23:in `<main>'
UPD: ./resized is a proper JPEG file:
% file ./resized
./resized: JPEG image data, JFIF standard 1.01, comment: "CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 80"
URI encoding is not enough. You also need to encode: , / ? : # & = + $ #.
Try:
URI.escape(IO.binread('./resized'), Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))

Resources