Extract REST API request json value to variable in RestAssured - rest-assured

We have to validate the value sent in our REST API request payload with Response value, Tried the below and was able to get the JSON array printed. How to get the specific object inside the array of the request JSON body.
Request Payload :
{
"Testinfo":{
"abc":2,
"xyz":"2020-01-01"
},
"Details":{
"eductation":{
"test1":9,
"test2":100,
"test3":50
},
"neweductiona":{
"test1":"value",
"test2":"Draws"
}
}
}
Code :
jsonObject = (JSONObject) JSONValue.parse(request);
JSONObject Testinfo = (JSONObject) jsonObject.get("Testinfo");
JSONObject Details = (JSONObject) jsonObject.get("Details");
System.err.println("Testinfo value in the request is: " + Testinfo);
System.err.println("Details value in the request is: " + Details);
Output :
{
"abc":2,
"xyz":"2020-01-01"
},
{
"eductation":{
"test1":9,
"test2":100,
"test3":50
},
"neweductiona":{
"test1":"value",
"test2":"Draws",
}
How to get specific value such as "Details.eductation.test3"
Tried below
JSONArray jsonArray = (JSONArray) JSONValue.parse(request)
but getting an error as :
java.lang.ClassCastException: net.minidev.json.JSONObject cannot be cast to net.minidev.json.JSONArray
Please guide.

Use JSONPath
String json = "{\r\n" + " \"Testinfo\": {\r\n" + " \"abc\": 2,\r\n"
+ " \"xyz\": \"2020-01-01\"\r\n" + "\r\n" + "\r\n" + " },\r\n" + "\r\n" + " \"Details\": {\r\n"
+ " \"eductation\": {\r\n" + " \"test1\": 9,\r\n" + " \"test2\": 100,\r\n"
+ " \"test3\": 50\r\n" + " },\r\n" + " \"neweductiona\": {\r\n"
+ " \"test1\": \"value\",\r\n" + " \"test2\": \"Draws\",\r\n"
+ " \"test3\": 50\r\n" + "\r\n" + " }\r\n" + " }\r\n" + "}";
JsonPath js = new JsonPath(json);
System.out.println("Value is : "+js.getString("Details.eductation.test3"));
Output :
Value is : 50

Related

ERR value is not an integer or out of range

I have this code in a lua script which I run from .net.
const string script = " if redis.call('EXISTS', '{0}') == 1 then" +
" local user = redis.call('get','{0}')" +
" local value = cjson.decode(user)" +
" value['UserPreferences'] = cjson.decode('{1}')" +
" value['Timestamp'] = cjson.decode('{2}')" +
" local val=cjson.encode(value)" +
" redis.call('set', '{0}', val)" +
" redis.call('EXPIRE', '{0}','{3}')" +
" end";
var redisScript = string.Format(script, "User_" + userId, JsonConvert.SerializeObject(userPreferences), JsonConvert.SerializeObject(DateTime.UtcNow), ConfigurationManager.AppSettings["RedisKeyExpiryTime"]);
await Cache.ScriptEvaluateAsync(redisScript);
This returns the error :
Error: ERR value is not an integer or out of range
please give some feedback to solve the issue.

GenericRecord to GenericRecord using sub schema (reader schema) without Encode/Decode

I am trying an efficient way to create a GenericRecord from another GenericRecord using a subschema (reader schema) without using Encoder/Decoder. For example I have the following schemas
String fullSchema = "{\"namespace\": \"example.avro\",\n" +
" \"type\": \"record\",\n" +
" \"name\": \"User\",\n" +
" \"fields\": [\n" +
" {\"name\": \"name\", \"type\": \"string\"},\n" +
" {\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]},\n" +
" {\"name\": \"favorite_number2\", \"type\": [\"int\", \"null\"]},\n" +
" {\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]}\n" +
" ]\n" +
"}";
String readerSchema = "{\"namespace\": \"example.avro\",\n" +
" \"type\": \"record\",\n" +
" \"name\": \"User\",\n" +
" \"fields\": [\n" +
" {\"name\": \"name\", \"type\": \"string\"},\n" +
" {\"name\": \"favorite_number2\", \"type\": [\"int\", \"null\"]}\n" +
" ]\n" +
"}";
I would like to find a way to do something like this without any code and decoder, I know it is possible using a reader schema but because performance reasons, I would like to avoid this option, my real schemas are much more bigger and complex (nested structures and arrays)
GenericRecord record = new GenericData.Record(new Schema.Parser().parse(fullSchema));
record.put("name", "Jhon");
record.put("favorite_number", 1);
record.put("favorite_number2", 2);
record.put("favorite_color", "red");
GenericRecord subRecord = copy(record, readerSchema);

Google Adwords Reporting HTTP POST request returns 400 response code

I am trying to use Google Adwords Reporting HTTP POST request to retrieve stats for a list of keywords that could exist under multiple Campaigns/Adgroups. This is the API documentation that I was referring to https://developers.google.com/adwords/api/docs/guides/reporting#prepare-the-http-post-request.
Below is scala code that returns 400 error code. What am I doing wrong ? Or is there another way of retrieving data from KEYWORDS_PERFORMANCE_REPORT report type ?
val httpClient = new DefaultHttpClient()
val postRequest=new HttpPost("https://adwords.google.com/api/adwords/reportdownload/v201605")
postRequest.addHeader("Host","adwords.google.com")
postRequest.addHeader("User-Agent", "curl, gzip")
postRequest.addHeader("Accept","*/*")
postRequest.addHeader("Expect","100-continue")
postRequest.addHeader("Accept-Encoding","gzip")
postRequest.addHeader("Content-Type","multipart/form-data; boundary=------------------------12d01fae60c7b559; charset=utf-8")
postRequest.addHeader("Authorization","Bearer 1/*************************************")
postRequest.addHeader("developerToken","/*************************************")")
postRequest.addHeader("clientCustomerId","/*************************************")")
postRequest.addHeader("Parameters","__rdxml: <?xml version=\"1.0\" " +
"encoding=\"UTF-8\"?>" +
"<reportDefinition>" +
" <selector>" +
" <fields>CampaignId</fields>" +
" <fields>AdGroupId</fields>" +
" <fields>Id</fields>" +
" <fields>Criteria</fields>" +
" <fields>CriteriaType</fields>" +
" <fields>Impressions</fields>" +
" <fields>Clicks</fields>" +
" <fields>Cost</fields>" +
" <predicates>" +
" <field>Status</field>" +
" <operator>NOT_IN</operator>" +
" <values>PAUSED</values>" +
" </predicates>" +
" </selector>" +
" <reportName>Criteria performance report #56bd904878715</reportName>" +
" <reportType>CRITERIA_PERFORMANCE_REPORT</reportType>" +
" <dateRangeType>LAST_7_DAYS</dateRangeType>" +
" <downloadFormat>CSV</downloadFormat>" +
"</reportDefinition>")
val httpResponse=httpClient.execute(postRequest)
println(httpResponse.getStatusLine.toString)
Your report definition should go into the POST request's body encoded either as application/x-www-form-urlencoded or multipart/form-data—in your code you are adding it as a header called Parameters.

Rails: sending data to asana and getting a syntax error

assign task to Asana
require "rubygems"
require "JSON"
require "net/https"
api_key = "1wPBetR9.6bhINO7xO9ypG6iP2aYU8hx"
workspace_id = "5386494137624"
assignee = "craig#theaerialistpress.com"
# set up HTTPS connection
uri = URI.parse("https://app.asana.com/api/1.0/tasks")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
# set up the request
header = {
"Content-Type" => "application/json"
}
req = Net::HTTP::Post.new(uri.path, header)
req.basic_auth(api_key, '')
req.body = {
"data" => {
"workspace" => workspace_id,
"name" => "House Order: " + #order.name,
"assignee" => assignee,
"projects" => "35978729781365",
"notes" => "Name: " + #order.name +
"\nEmail: " + #order.email +
"\nEvent Date: " + #date.to_s +
"\nDesign: " + #order.design +
"\n\nPaper Color: " + #order.paper_color +
"\nFont #1: " + #order.font1 +
"\nFont #2: " + #order.font2 +
if #order.card_type1 != "none"
"\n\nCard #1: " + #order.card_type1 + "\nPaper Weight: " + #order.paper_weight1 + "\nQuantity: " + #order.quantity1 + "\nInk Color #1: " + #order.ink_color11 + "\nInk Color #2: " + #order.ink_color12 + "\nWording: " + #order.wording1 + "\nReturn Address Printing: " + #order.return_address1 + "\nGuest Address Printing: " + #order.guest_address1.to_s + "\nEnvelope Liners: " + #order.envelope_liners1
end
if #order.card_type2 != "none"
"\n\nCard #2: " + #order.card_type2 + "\nPaper Weight: " + #order.paper_weight2 + "\nQuantity: " + #order.quantity2 + "\nInk Color #2: " + #order.ink_color21 + "\nInk Color #2: " + #order.ink_color22 + "\nWording: " + #order.wording2 + "\nReturn Address Printing: " + #order.return_address2 + "\nGuest Address Printing: " + #order.guest_address2.to_s + "\nEnvelope Liners: " + #order.envelope_liners2
end
}
}.to_json()
# issue the request
res = http.start { |http| http.request(req) }
# output
body = JSON.parse(res.body)
if body['errors'] then
puts "Server returned an error: #{body['errors'][0]['message']}"
else
puts "Created task with id: #{body['data']['id']}"
end
I am getting a syntax error when I am using if statements inside the data I am sending to asana. I am very new at rails and not sure what I am doing wrong.
This is the error:
syntax error, unexpected keyword_if, expecting '}' if #order.card_type2 != "none" ^ /Users/craigrinde/Dropbox/top_secret/aerialist/app/controllers/orders_controller.rb:212: syntax error, unexpected '}', expecting keyword_end } ^

Twitter API link parser

I am having an issue and tried to do everything regarding this!! even HttpUtility.ParseQueryString won't help!
I am trying to parse twitter links coming from the API in the form of http://t.co/oEVQbihMWu. I need the fully resolved URL.
My code:
richTextBox1.Clear();
richTextBox1.Visible = true;
SearchOptions SO = new SearchOptions();
SO.GeoCode = richTextBox3.Text + "," + richTextBox2.Text + "mi";
TwitterResponse<TwitterSearchResultCollection> TweetSearchResult = TwitterSearch.Search(tokens, "#blogger", SO);
if (TweetSearchResult.Result != RequestResult.Success) richTextBox1.Text = "connection Error";
else
{
string a = null;
foreach (var tweet in TweetSearchResult.ResponseObject)
{
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, tweet.User.Website, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + tweet.User.Website + "\n" + tweet.Text + "\n\n\n");
}
links being represented by tweet.user.website.
any help? :)
In the API response, there is entities.urls which contains an array of url and expanded_url mappings. Check your library's documentation for equivalent.
Alternatively, if you inspect the response for t.co links, you will find this:
<noscript><META http-equiv="refresh" content="0;URL=http://www.fitnessbydanielle.com"></noscript><title>http://www.fitnessbydanielle.com</title><script>window.opener = null; location.replace("http:\/\/www.fitnessbydanielle.com")</script>
Parse it to get the url.
I managed to crack it.
What I did:
foreach (var tweet in TweetSearchResult.ResponseObject)
{
if(tweet.User.Website != null)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(tweet.User.Website);
req.AllowAutoRedirect = false;
var resp = req.GetResponse();
string realUrl = resp.Headers["Location"];
string b = tweet.User.Location.Contains(",") ? tweet.User.Location.Replace(",", "-") : tweet.User.Location;
a += string.Format("{0},{1},{2},{3},{4},{5},{6},{7}", tweet.CreatedDate, b, tweet.User.Id,
tweet.User.ScreenName, tweet.User.Name, tweet.User.NumberOfFollowers, realUrl, Environment.NewLine);
richTextBox1.AppendText(" " + tweet.CreatedDate + "\n" + tweet.User.Location + "\n" + tweet.User.Id + "\n" + tweet.User.ScreenName + "\n" + tweet.User.Name + "\n" + tweet.User.NumberOfFollowers +
"\n" + realUrl + "\n" + tweet.Text + "\n\n\n");
}
}
File.AppendAllText(#".\BloggerTable.csv", a, Encoding.UTF8);
}
Wrapped it inside a condition so no users without website will show and used a webrequest to get the link. stored the location inside the httprequest header for each and every tweet.

Resources