How to pass the json response in ResponseBody of WireMock - wiremock

I am trying to validate the json response. Have gone through the documentation in wiremock and also tried github example as below syntax.
https://github.com/tomakehurst/wiremock/blob/master/src/test/java/ignored/Examples.java#374
#Test
public void toDoListScenario() {
stubFor(get(urlEqualTo("/todo/items")).inScenario("To do list")
.whenScenarioStateIs(STARTED)
.willReturn(aResponse()
.withBody("<items>" +
" <item>Buy milk</item>" +
"</items>"))); }
How to enter the json response in Body Section.
{
employeeDetails : [
employeeName : ABCDE,
employeeID : 12345 ]
}
Is the below representation is correct. Please help me on this.
.withBody("employeeDetails:" +
"employeeID" : "12345" +
"employeeName" : "Preethi" + )

Just format the text as json:
.withBody("{\"employeeDetails\":[" +
"\"employeeID\" : \"12345\"" +
"\"employeeName\" : \"Preethi\"]}")
and set the header to
.withHeader("Content-Type", equalTo("application/json"))

Related

Groovy rest client without libraries

I am using a rest client to do Post
My code is
def postRequest() {
def message = "{ \"fields\": { \"project\": { \"id\": \"001\" },\"summary\": \"Test Issue For Jira Integration\",\"description\": \"Creating of an issue for for projects and issue types using the REST API\", \"issuetype\": { \"id\": \"5\" } }}"
// POST
def post = new URL("https://jira/rest/api/latest/issue").openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
post.setRequestProperty ("Authorization", basicAuth);
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(201)) {
println(post.getInputStream().getText());
}else
{
println(post.getInputStream().getText());
print(postRC)
}
}
I am getting 400 error code , where its getting wrong
I am successfully able to do the get request with URL
400 = bad request.
it means server tried to validate your post data and it's wrong.
usually this response contains body with explanation...
for 400+ status codes the body comes through getErrorStream() and not through getInputStream()
So, I would do it like this:
def postRequest(url, message) {
def post = new URL(url).openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + userpass.getBytes("UTF-8").encodeBase64()
post.setRequestProperty("Authorization", basicAuth);
post.setRequestProperty("Content-Type", "application/json")
post.setDoOutput(true)
if( !(message instanceof String) )message = new groovy.json.JsonBuilder(message).toPrettyString()
post.getOutputStream().write(message.getBytes("UTF-8"))
def response=[:]
response.code = post.getResponseCode()
response.message = post.getResponseMessage()
if( response.code>=400 ){
try{
response.body = post.getErrorStream()?.getText("UTF-8")
}catch(e){}
}else{
response.body = post.getInputStream()?.getText("UTF-8")
}
assert response.code in [200,201] : "http call failure ${response.code}: ${ response.body ?: response.message }"
return response
}
def msg = [
fields: [
project : [ id: "001" ],
summary : "Test Issue For Jira Integration",
description : "Creating of an issue for for projects and issue types using the REST API",
issuetype : [ id: "5" ]
]
]
def r = postRequest("http://httpbin.org/post", msg)
println r
The issue was related to certificate , I have to bypass the certificate validation and its working fine. Since both the application are under same network and behind same company's firewall , I have bypass the certificate validations.
Adding the skipping certificate validation part to the above code is working for me

How do I get the value of collection.find(connect.data).fetch()?

I am trying to create a meteor RESTful API for my app based on this The Meteor Chef online tutorial. The HTTP package is installed in the beginning of the tutorial, in order to test the RESTful API once the API development is completed.
I am currently in the testing phase and cant seem to get my GET Methods used to retrieve data from my collection to work.
Find below my GET Method code:
methods: {
pescrow: {
GET: function( context, connection ) {
var hasQuery = API.utility.hasData( connection.data );
console.log("hasQuery value == " +hasQuery+ " on line 183");
if ( hasQuery ) {
connection.data.owner = connection.owner;
console.log("Your in GET::hasQuery: Line 187 " + connection.data );
var getPescrows = recipientsDetails.find( connection.data ).fetch();
console.log("getPescrows value: " +getPescrows+ " Line 203");
if ( getPescrows.length > 0 ) {
// We found some pescrows, we can pass a 200 (success) and return the
// found pescrows.
console.log("getPescrows found Line 205");
API.utility.response( context, 200, getPescrows );
}
else {
console.log("getPescrows NOT found Line 208!");
// Bummer, we didn't find any pescrows. We can pass a 404 (not found)
// and return an error message.
API.utility.response( context, 404, { error: 404, message: "No Pescrows found, dude." } );
}
}
else {
// Our request didn't contain any params, so we'll just return all of
// the pescrows we have for the owner associated with the passed API key.
var getPescrows = recipientsDetails.find( { "owner": connection.owner } ).fetch();
API.utility.response( context, 200, getPescrows );
}
}
}
}
I test my API via the Chrome console by pasting in the below code:
HTTP.get( "http://localhost:8000/paymentC2B/v1", {
params: {
"api_key": "b21d83ef267bd829a9d732551270c718",
"paymentStatus": "Pending",
"recipientNumber" : "0705087633"
}
}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
And the response I get in the terminal is:
hasQuery == true Line 183
Your in GET::hasQuery: Line 187 [object Object]
getPescrows value: Line 203
getPescrows NOT found Line 208!
When I run the query below in the console it successfully yields:
recipientsDetails.find({paymentStatus:"Pending", recipientNumber: "0705087633"}, {sort: {paymentDate: 'desc' }}).fetch()
Showing:
[{…}]
0
:
key : "b21d83ef267bd829a9d732551270c718"
paymentDate : "2018-04-02 15:15:49"
paymentStatus : "Pending"
recipientAmount : "500"
recipientNumber : "0705087633"
_id : "uSsCbdBmmhR2AF2cy"
__proto__ : Object
length : 1
__proto__ : Array(0)
It seems like the issue is in the recipientsDetails.find( connection.data ).fetch(); query. Can someone kindly point out where I am going wrong in my code?
Looking forward to your response.
When you test your params include api_key. I'm betting this key does not appear in your recipientsDetails collection.
Instead of just doing:
connection.data.owner = connection.owner;
Try:
connection.data.owner = connection.owner;
delete connection.data.api_key;

How to create persistent rooms in openfire using strophe?

I'm using the following iq message to create persistent rooms in openfire:
var configiq = $iq({
to : chatObj.getActiveChatRoomName() + "#" + chatObj.groupChatService,
type : "set"
}).c("x", {
xmlns : "jabber:x:data",
type : "submit"
}).c('field', {
"var" : "FORM_TYPE"
})
.c('value').t("http://jabber.org/protocol/muc#roomconfig")
.up().up()
.c('field', {
"var" : "muc#roomconfig_persistentroom"
})
.c('value').t("1");
chatObj.connection.sendIQ(configiq.tree(), function () {
console.log('success');
}, function (err) {
console.log('error', err);
});
But, I am getting the following error:
error <iq xmlns=​"jabber:​client" type=​"error" id=​"1356:​sendIQ" from=​"msrtc0711#conference.stslp239" to=​"ashishjmeshram#stslp239/​ax8nb2atg1">​<x xmlns=​"jabber:​x:​data" type=​"submit">​…​</x>​<error code=​"400" type=​"modify">​<bad-request xmlns=​"urn:​ietf:​params:​xml:​ns:​xmpp-stanzas">​</bad-request>​</error>​</iq>​
Using the Strophe.muc plugin is easier:
1) firstly join the room (this creates an instant room):
connection.muc.join(room_jid, nick);
2) then create a "configured room", eventually with a subject and a description associated:
var config = {"muc#roomconfig_publicroom": "1", "muc#roomconfig_persistentroom": "1"};
if (descr) config["muc#roomconfig_roomdesc"] = descr;
if (subject) config["muc#roomconfig_subject"] = subject;
connection.muc.createConfiguredRoom(room_jid, config, onCreateRoomSuccess, onCreateRoomError);
A working example is available here: http://plnkr.co/edit/Mbi15HDZ2yW5vXskS2X6?p=preview

Making POST Requests in Backbone.js

I have a RESTful server, which accepts url encoded parameters.
In my case, making a post request to https:// my server:8443/test/auth
Set the request header as
Content-Type : application/x-www-form-urlencoded
and passing the parameters
username=myusername
password=mypassword
works and gives the desired response.
I want to achieve the same using Backbonejs. So, I have
Person = Backbone.Model.extend({
initialize: function() {
this.on('all', function(e) { console.log(this.get('name') + " event " + e );
});
},
urlRoot: "https:// my server:8443/test/authauth",
url : function(){
var base = this.urlRoot;
return base + ""
}
});
var person = new Person({ "username" : "myusername" , "password":"mypassword" });
person.save(null, {
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}}
);
But, it says that no username and password attributes are not present. Waht is the correct way to pass the paramteres in url encoded form in Backbone.js
Thanks

Cypher query via the REST endpoint : relationship not created

I'm using Neo4j 2.0.1 Community. I try to insert a relationship in the graph by sending the query through the REST endpoint.
My relationship query is very simple:
MATCH (t1:Test { name : 'TEST_1' }), (t2:Test { name : 'TEST_2' }) CREATE (t1)-[:REL_TEST]->(t2)
I call it this way in Powershell:
$postParams = "{ `"query`" : `"MATCH (t1:Test { name : {test1} }), (t2:Test { name : {test2} }) CREATE (t1)-[:REL_TEST]->(t2)`",`"params`" : { `"test1`" : `"TEST_1`", `"test2`" : `"TEST_2`" } }"
Invoke-WebRequest -Uri http://localhost:7474/db/data/cypher -Method POST -Body $postParams -Headers #{"Accept"="application/json; charset=UTF-8";"Content-Type"="application/json"}
And I got the following response:
StatusCode : 200
StatusDescription : OK
Content : {
"columns" : [ ],
"data" : [ ]
}
RawContent : HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Length: 40
Content-Type: application/json; charset=UTF-8
Server: Jetty(9.0.z-SNAPSHOT)
{
"columns" : [ ],
"data" : [ ]
}
Forms : {}
Headers : {[Access-Control-Allow-Origin, *], [Content-Length, 40], [Content-Type, application/json; charset=UTF-8], [Server, Jetty(9.0.z-SNAPSHOT)]}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 40
But the relationship is not created. If I then type the same query in the browser UI, it works.
I don't get what I'm an doing wrong, especially since the query works in the browser and the REST calling procedure works for inserting a node for example.
Are you certain that your query is not working. You are not returning any data so it's possible it is being created without your knowing it.
You could try something like this
MATCH (t1:Test{name: {test1}}), (t2:Test{name: {test2}})
CREATE (t1)-[rel:REL_TEST]->(t2)
RETURN rel
If you don't get the rel in your response it means the rel wasn't created probably because at least one of the MATCHes failed. Try returning t1 and t2 as well to see if they are working as expected.