How to solve this error " (pre:svcFault) Service Fault"? - ruby-on-rails

I am trying to call a SOAP api using Savon gem. I am getting the following error: "(pre:svcFault) Service Fault"
I created both the header and message for the request.
Here is the request sent from SoapUI: SoapUI request.
i am getting a true response from SoapUI.
My code is shown below:
class SoapApi
require 'savon'
def self.initialize
header = {
"ebmCID" => "9366498d-bc79-4fad-be2b-fa1a0e84241a",
"ebmMID" => "9366498d-bc79-4fad-be2b-fa1a0e84241a",
"ebmRTID" => "9366498d-bc79-4fad-be2b-fa1a0e84241a",
"ebmSID" => "FMobile-FCUBS",
"ebmTimestamp" => "2019-06-10T12:27:46.1623586Z",
}
message = {
customerId: '00653473'
}
client = Savon.client(
:wsdl => "https://192.168.176.103:8012/tevs/pp.pm.evs.Customer_1.2?wsdl",
:ssl_verify_mode => :none
)
response = client.call(
:get_account_list,
:soap_header => header,
:message => message
)
return response
end
end
And here i am calling the above method:
#index.html.erb
<%=
SoapApi.initialize
puts #response
%>

Where you able to create a valid call using SoapUI (https://www.soapui.org.)? Try this first and make it work.
Next create a call from a plain ruby script - without Rails - which sends the same functional XML as you did in SoapUI before.
Third embed this code into your RoR application.
You can put the following in your client definition for better logging:
client = Savon.client(
:wsdl => "https://192.168.176.103:8012/tevs/pp.pm.evs.Customer_1.2?wsdl",
:ssl_verify_mode => :none,
log: true,
log_level: :debug,
pretty_print_xml: true
)
Compare the output with your working SoapUI example.

Related

The content type 'application/x-www-form-urlencoded' is not supported in Ruby on Rails

So I'm just trying to make a simple post request using httpclient in RoR.
I'm going through a proxy, doing ntlm authentication with the server ( I can make GET requests without a problem).
Now when I try and do a post request, I get the error mentioned in the title...
proxy = ENV['HTTP_PROXY']
client=HTTPClient.new(proxy)
client.set_auth(nil,user,pass)
body= [{'Content-Type' => 'application/atom+xml, :content => ...}]
res = client.post('url',body)
puts res.body
How am i getting this error when I clearly specify the header as atom+xml..?
You should use
res = client.post('url',
:body => "...body content...",
:header => {'Content-Type' => 'application/atom+xml'})

How to tag every log call in rails with request id (lograge)

I'm using lograge with rails and I have configured my logs using JSON format. I would like every time I call logger.info,logger.warn, etc. to include the request uuid. The way rails handles this with tagged logging falls short of what I would like because it does not seem able to merge the request uuid with the remainder of the JSON payload, instead prepending it on the line in non-JSON format.
For instance, if I call logger.info(client: :ig) I would expect the following log output:
{"request_id": <request uuid>, "client": "ig"}
But instead rails will prepend the request uuid (when configured via config.log_tags = [:uuid]) like so:
[<request uuid>] {"client": "ig"}
Does anyone know if there is a way to get the tagging behavior to merge with the JSON payload instead of prepending it on the same line? I'd like to configure our logs to forward to Splunk using just a simple JSON formatter and not deal with this prepending format.
Also, I have configured lograge to include request_id set to the request uuid in a lambda passed to custom_options in config/application.rb. This works but only when rails logs the request. If I explicitly call one of the logging methods anywhere else, the request_id is not included.
# application.rb
config.lograge.enabled = true
config.lograge.formatter = Lograge::Formatters::Json.new
config.lograge.custom_options = lambda do |e|
{
params: e.payload[:params].except("controller", "action", "utf8"),
request_id: e.payload[:request_id] # added this in `append_info_to_payload` in ApplicationController
}
end
Then in config/environments/production.rb
config.log_tags = [ -> (req) { { request_id: req.env["action_dispatch.request_id"] } } ]
Any help is appreciated, thanks.
The problem is that the payload doesn't have the request_id.
As you can see in:
./actionpack-3.2.11/lib/action_controller/metal/instrumentation.rb:18-25
raw_payload = {
:controller => self.class.name,
:action => self.action_name,
:params => request.filtered_parameters,
:format => request.format.try(:ref),
:method => request.method,
:path => (request.fullpath rescue "unknown")
}
I override this method (copy ./actionpack-3.2.11/lib/action_controller/metal/instrumentation.rb in config/initializer.rb) and add your param.
raw_payload = {
:controller => self.class.name,
:action => self.action_name,
:params => request.filtered_parameters,
:format => request.format.try(:ref),
:method => request.method,
:path => (request.fullpath rescue "unknown"),
:request_id => env["action_dispatch.request_id"]
}
Maybe there are a better way for override instrumentation, but it is enough.
Is easier to override initializer with class_eval as you can see in:
Access to Rails request inside ActiveSupport::LogSubscriber subclass

Ruby: HTTParty: can't format XML POST data correctly?

NOTE: "object" is a placeholder work, as I don't think I should be saying what the controller does specifically.
so, I have multiple ways of calling my apps API, the following works in the command line:
curl -H 'Content-Type: application/xml' -d '<object><name>Test API object</name><password>password</password><description>This is a test object</description></object>' "http://acme.example.dev/objects.xml?api_key=1234"
the above command generates the following request in the devlog:
Processing ObjectsController#create to xml (for 127.0.0.1 at 2011-07-07 09:17:51) [POST]
Parameters: {"format"=>"xml", "action"=>"create", "api_key"=>"1234", "controller"=>"objects",
"object"=>{"name"=>"Test API object", "description"=>"This is a test object", "password"=>"[FILTERED]"}}
Now, I'm trying to write tests for the actions using the API, to make sure the API works, as well as the controllers.
Here is my current (broken) httparty command:
response = post("create", :api_key => SharedTest.user_api_key, :xml => data, :format => "xml")
this command generates the following request in the testlog:
Processing ObjectsController#create to xml (for 0.0.0.0 at 2011-07-07 09:37:35) [POST]
Parameters: {
"xml"=>"<object><name><![CDATA[first post]]></name>
<description><![CDATA[Things are not as they used to be]]></description>
<password><![CDATA[WHEE]]></password>
</object>",
"format"=>"xml",
"api_key"=>"the_hatter_wants_to_have_tea1",
"action"=>"create",
"controller"=>"objects
So, as you can see, the command line command actually generates the object hash from the xml, whereas the httparty command ends up staying in xml, which causes problems for the create method, as it needs a hash.
Any ideas / proper documentation?
Current documentation says that post takes an url, and "options" and then never says what options are available
**EDIT:
as per #Casper's suggestion, my method now looks like this:
def post_through_api_to_url(url, data, api_key = SharedTest.user_api_key)
response = post("create", {
:query => {
:api_key => api_key
},
:headers => {
"Content-Type" => "application/xml"
},
:body => data
})
ap #request.env["REQUEST_URI"]
assert_response :success
return response
end
unfortunately, the assert_response fails, because the authentication via the api key fails.
looking at the very of of the request_uri, the api_key isn't being set properly... it shows:
api_key%5D=the_hatter_wants_to_have_tea1"
but it should just be equals, without the %5D (right square bracket)
I think this is how you're supposed to use it:
options = {
:query => {
:api_key => 1234
},
:headers => {
"Content-Type" => "application/xml"
},
:body => "<xmlcode>goes here</xmlcode>"
}
post("/create", options)
Forgive me for being basic about it but if you only want to send one variable as a parameter, why don't you do as Casper suggests, but just do:
post("/create?api_key=1234", options)
Or rather than testing HTTParty's peculiarities in accessing your API, perhaps write your tests using Rack::Test? Very rough example...
require "rack/test"
require "nokogiri"
class ObjectsTest < Test::Unit::TestCase
include Rack::Test::Methods
def app
MyApp.new
end
def create_an_object(o)
authorize "x", "1234" # or however you want to authenticate using query params
header 'Accept', 'text/xml'
header 'Content-Type', 'text/xml'
body o.to_xml
post "/create"
xml = Nokogiri::XML(last_response.body)
assert something_logic_about(xml)
end
end

Integrate Jasper in Rails 3

I'm trying to integrate a rails 3 app with jasper following this wiki:
http://wiki.rubyonrails.org/rails/pages/HowtoIntegrateJasperReports
But it seems that a lot of information isn't updated so it's been very hard to make it work by myself. I've also read a topic at ruby-forum: http://www.ruby-forum.com/topic/139453
with some details explained but still couldn't make it work.
My first problem is related with the render_to_string method:
When the controller method runs I receive a "Template is missing" error:
this is the method:
def report
#customers = Customer.all
send_doc(render_to_string(:template => report_customers_path, :layout => false), '/pdfs', 'report.jasper', "customers", 'pdf')
end
Although this seems simple I'm not understanding why is this happening. Doesn't render_to_string with layout => false suposed to get me the string result of that action?
I also tried :action instead of :template, but it does the same.
If anybody with some expertise with this integration could help...
Thanks in advance,
André
We actually use jasperreports to create reports, and recently upgraded to Rails 3.0. To create the xml, we use xml.erb templates. Jasper reports runs in a separate glassfish server Here's the general idea:
url = URI.parse(my_url_string)
dataxml = render_to_string(:template => my_template_name).gsub(/\n/, '')
params = {'type' => 'pdf', 'compiledTemplateURI' => my_jasper_file, 'data' => dataxml }
request = Net::HTTP::POST.new(url.request_uri)
request.set_form_data(params)
obj = Net::HTTP.new(url.host, url.port)
obj.read_timeout = my_timeout_setting
response = obj.start { |http| http.request(request) }
case response
when Net::HTTPOK
send_data(response.body, :filename => my_chosen_filename, :type => "application/pdf", :disposition => "inline")
else
raise "failed to generate report"
end
I don't know anything about jasper, but it sounds like you want to do two things: render a PDF template and then send the raw output back w/ a PDF mime type:
pdf_contents = render_to_string(:template => 'users/report')
send_data(pdf_contents, :file_name => 'report.pdf', :type => 'application/pdf')
You're passing in the external URL as the template path, but that's probably wrong if you're getting errors about the template path. Fix the template path first.
Use savon to interact with jaserserver in rails3.
Here is an example:
require 'logger'
require 'savon'
logger = Logger.new(STDOUT)
logger.info "Test jasper via Savon-SOAP"
#client = Savon::Client.new {
wsdl.document = "http://localhost:8080/jasperserver/services/repository?wsdl"
http.auth.basic "jasperadmin", "jasperadmin"
}
logger.info "runReport method"
begin
result = #client.request :run_report do
soap.body = "<requestXmlString>
<![CDATA[
<request operationName='runReport' >
<argument name='RUN_OUTPUT_FORMAT'>PDF</argument>
<resourceDescriptor name='' wsType='' uriString='/reports/samples/AllAccounts' isNew='false'>
<label></label>
</resourceDescriptor>
</request>
]]>
</requestXmlString>"
end
send_data result.http.raw_body, :type => 'application/pdf', :filename => 'report.pdf', :disposition => 'attachment'
rescue Exception => e
logger.error "SOAP Error: #{e}"
end
Try to change the render_to_string() code to this:
#customers.to_xml

Changing Content-Type to JSON using HTTParty

I am trying to use Ruby on Rails to communicate with the Salesforce API. I can fetch data easily enough but I am having problems posting data to the server. I am using HTTParty as per Quinton Wall's post here:
https://github.com/quintonwall/omniauth-rails3-forcedotcom/wiki/Build-Mobile-Apps-in-the-Cloud-with-Omniauth,-Httparty-and-Force.com
but all I seem to be able to get from the salesforce server is the error that I am submitting the body as html
{"message"=>"MediaType of 'application/x-www-form-urlencoded' is not supported by this resource", "errorCode"=>"UNSUPPORTED_MEDIA_TYPE"}
the responsible code looks like:
require 'rubygems'
require 'httparty'
class Accounts
include HTTParty
format :json
...[set headers and root_url etc]
def self.save
Accounts.set_headers
response = (post(Accounts.root_url+"/sobjects/Account/", :body => {:name => "graham"}.to_json))
end
end
anyone have an idea why the body should be being posted as html and how to change this so that it definitely goes as json so that salesforce doesn't reject it?
Any help would be appreciated. cheers
The Content-Type header needs to be set to "application/json". This can be done by inserting :headers => {'Content-Type' => 'application/json'} as a parameter to post, ie:
response = post(Accounts.root_url+"/sobjects/Account/",
:body => {:name => "graham"}.to_json,
:headers => {'Content-Type' => 'application/json'} )
You have to set the Content-Type header to application/json. I haven't used HTTParty, but it looks like you have to do something like
response = (post(Accounts.root_url+"/sobjects/Account/", :body => {:name => "graham"}.to_json) , :options => { :headers => { 'Content-Type' => 'application/json' } } )
I'm somewhat surpised that the format option doesn't do this automatically.

Resources