Spring MVC 3.1 REST services post method return 415 - rest

I'm doing a Spring MVC controller and I still get problem with POST operation.
I've read many solutions on stackoverflow without to fix my problem.
My achievement at the moment :
I sent a GET request with an Id and return an Object converted to JSON successfully.
I failed to send a POST request with a JSON body, return = 415 UNSUPPORTED_MEDIA_TYPE
1) I added to my pom.xml the Jackson API : 1.8.5
2) My Spring configuration file:
I added all necessary parts :
viewResolver
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
MappingJacksonHttpMessageConverter
mvc:annotation-driven
scan my controllers
3) My model object is simple : an Account with Id, Name and an amount
#Document
public class Account implements Serializable {
private static final long serialVersionUID = 9058933587701674803L;
#Id
private String id;
private String name;
private Double amount=0.0;
// and all get and set methods
4) and finally my simplified Controller class :
#Controller
public class AdminController {
#RequestMapping(value="/account", method=RequestMethod.POST,
headers = {"content-type=application/json"})
#ResponseStatus( HttpStatus.CREATED )
public void addAccount(#RequestBody Account account){
log.debug("account from json request " + account);
}
#RequestMapping(value="/account/{accountId}", method=RequestMethod.GET)
#ResponseBody
public Account getAccount(#PathVariable("accountId") long id){
log.debug("account from json request " + id);
return new Account();
}
}
5) On client side I've just executed curl commands :
The successfully GET command :
curl -i -GET -H 'Accept: application/json' http://myhost:8080/compta/account/1
The POST command which failed:
curl -i -POST -H 'Accept: application/json' -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account
Any ideas where I'm going wrong?

Well, "UNSUPPORTED_MEDIA_TYPE" should be a hint. Your curl command is actually sending:
Content-Type: application/x-www-form-urlencoded
Simply add explicit Content-Type header and you're good to go:
curl -v -i -POST -H 'Accept: application/json' -H 'Content-Type: application/json' -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account

Try this :
curl -i -POST -H "Accept: application/json" -H "Content-type: application/json" -d '{"id":1,"name":"test",amount:"0.0"}' http://myhost:8080/compta/account

Related

Request body matching with XML declaration in Wiremock-standalone

I have a stub described in the ./mappings/*.json file.
"request": {
"method": "POST",
"url": "/some/thing",
"bodyPatterns" : [ {
"matchesXPath" : {
"expression": "//nodeA/text()",
"contains": "999"
}
} ]
}
Wiremock (ver.2.26.2) is started in standalone mode.
When I call the service like this:
curl -d "<request><nodeA>999</nodeA></request>" -X POST http://localhost:8888/some/thing
I am getting the response from stub as expected. The problem is that the request has to be sent with XML declaration tag , e.g.
curl -d "<?xml version="1.0" encoding="UTF-8"?><request><nodeA>999</nodeA></request>" -X POST http://localhost:8888/some/thing
and in this case the request isn't matched. I tried to find smth in the documentation regarding it, but so far no luck
I found out that the problem was with curl that I used. It was malformed since I used same double quotes in XML declaration. Now I load the request body from file and everything works just fine
curl -H "Content-Type: application/xml" -d "#path_to_request_file" -X POST http://localhost:8888/some/thing

What is the format of the JSON for a Jenkins REST buildWithParameters to override the default parameters values

I am able to build a Jenkins job with its parameters' default values by sending a POST call to
http://jenkins:8080/view/Orion_phase_2/job/test_remote_api_triggerring/buildWithParameters
and I can override the default parameters "product", "suites" and "markers by sending to this URL:
http://jenkins:8080/view/Orion_phase_2/job/test_remote_api_triggerring/buildWithParameters?product=ALL&suites=ALL&markers=ALL
But I saw examples were the parameters can be override by sending a JSON body with new values. I am trying to do that by sending the following json bodies. Neither of them works for me.
{
'product': 'ALL',
'suites': 'ALL',
'markers': 'ALL'
}
and
{
"parameter": [
{
"name": "product",
"value": "ALL"
},
{
"name": "suites",
"value": "ALL"
},
{
"name": "markers",
"value": "ALL"
}
]
}
What JSON to send if I want to override the values of parameters "product", "suites" & "markers"?
I'll leave the original question as is and elaborate here on the various API calls to trigger parameterized builds. These are the calls options that I used.
Additional documentation: https://wiki.jenkins.io/display/JENKINS/Remote+access+API
The job contains 3 parameters named: product, suites, markers
Send the parameters as URL query parameters to /buildWithParameters:
http://jenkins:8080/view/Orion_phase_2/job/test_remote_api_triggerring/buildWithParameters?product=ALL&suites=ALL&markers=ALL
Send the parameters as JSON data\payload to /build:
http://jenkins:8080/view/Orion_phase_2/job/test_remote_api_triggerring/build
The JSON data\payload is not sent as the call's json_body (which is what confused me), but rater in the data payload as:
json:'{
"parameter": [
{"name":"product", "value":"123"},
{"name":"suites", "value":"high"},
{"name":"markers", "value":"Hello"}
]
}'
And here are the CURL commands for each of the above calls:
curl -X POST -H "Jenkins-Crumb:2e11fc9...0ed4883a14a" http://jenkins:8080/view/Orion_phase_2/job/test_remote_api_triggerring/build --user "raameeil:228366f31...f655eb82058ad12d" --form json='{"parameter": [{"name":"product", "value":"123"}, {"name":"suites", "value":"high"}, {"name":"markers", "value":"Hello"}]}'
curl -X POST \
'http://jenkins:8080/view/Orion_phase_2/job/test_remote_api_triggerring/buildWithParameters?product=234&suites=333&markers=555' \
-H 'authorization: Basic c2hsb21pb...ODRlNjU1ZWI4MjAyOGFkMTJk' \
-H 'cache-control: no-cache' \
-H 'jenkins-crumb: 0bed4c7...9031c735a' \
-H 'postman-token: 0fb2ef51-...-...-...-6430e9263c3b'
What to send to Python's requests
In order to send the above calls in Python you will need to pass:
headers = jenkins-crumb
auth = tuple of your (user_name, user_auth_token)
data = dictionary type { 'json' : json string of {"parameter":[....]} }
curl -v POST http://user:token#host:port/job/my-job/build --data-urlencode json='{"parameter": [{"name":"xx", "value":"xxx"}]}
or use Python request:
import requests
import json
url = " http://user:token#host:port/job/my-job/build "
pyload = {"parameter": [
{"name":"xx", "value":"xxx"},
]}
data = {'json': json.dumps(pyload)}
rep = requests.post(url, data)

Couchbase Cordova - doc_ids | Need to get uuids

I am trying to get the doc_ids in couchbase cordova to be in uuid format.
Currently, any doc that is inserted has _ids like - -AexsV4lbjOoH-AdlN1Fi0W , --mpIWIHza6CQEJEHRxPKba etc.
My setup is of such nature that the _ids need to be uuids as the cordova app will save the local DB as a part of a universal MongoDB on the server.
(So the DB on the server will have multiple local DBs stored). Hence, I need the _ids to be uuids
I did a quick research into how to create uuids in JS and found quite a few answers like -
/**
* Fast UUID generator, RFC4122 version 4 compliant.
* #author Jeff Ward (jcward.com).
* #license MIT license
* #link http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
**/
var UUID = (function() {
var self = {};
var lut = []; for (var i=0; i<256; i++) { lut[i] = (i<16?'0':'')+(i).toString(16); }
self.generate = function() {
var d0 = Math.random()*0xffffffff|0;
var d1 = Math.random()*0xffffffff|0;
var d2 = Math.random()*0xffffffff|0;
var d3 = Math.random()*0xffffffff|0;
return lut[d0&0xff]+lut[d0>>8&0xff]+lut[d0>>16&0xff]+lut[d0>>24&0xff]+'-'+
lut[d1&0xff]+lut[d1>>8&0xff]+'-'+lut[d1>>16&0x0f|0x40]+lut[d1>>24&0xff]+'-'+
lut[d2&0x3f|0x80]+lut[d2>>8&0xff]+'-'+lut[d2>>16&0xff]+lut[d2>>24&0xff]+
lut[d3&0xff]+lut[d3>>8&0xff]+lut[d3>>16&0xff]+lut[d3>>24&0xff];
}
return self;
})();
which generates uuids like d6414228-b07c-4bd2-9aa3-d1df8b548de6
So my question is - is there a direct way inside couchbase phonegap plugin to achieve this directly?
When writing a document to Couchbase Lite, you can either let the database pick a random ID (it will be unique) or specify one.
You can send a POST request to have the database generate the document ID.
curl -H 'Content-Type: application/json' \
-vX POST 'http://localhost:5984/app' \
-d '{"name": "john"}'
{"id":"-UwALc1GlcAcG60uag1oMf1","rev":"1-10dc5637dc2ccb55e007440cca73a415","ok":true}
Or a PUT request to specify one.
curl -H 'Content-Type: application/json' \
-vX PUT 'http://localhost:5984/app/john' \
-d '{"name": "john"}'
{"id":"john","rev":"1-10dc5637dc2ccb55e007440cca73a415","ok":true}
Note that from then on you must specify the revision number of the current revision to save updates on the document.
curl -H 'Content-Type: application/json' \
-vX PUT 'http://localhost:5984/app/john?rev=1-10dc5637dc2ccb55e007440cca73a415' \
-d '{"name": "johnny"}'

Angular2 - Unable to fetch using a 'where' condition in query to a REST API

I am working with Parse Server, and I am trying to fetch data using the REST API in my Angular2 application.
I am trying to fetch data according to a where condition, but I am not able to do so.
This is the code I am using:
constructor(http) {
var key = new URLSearchParams();
this.http = http;
this.disho = null;
key.set('where', {"estTime":"5min"});
this.http.get('https://parseapi.example.com/classes/Setto', { where : key }).subscribe(data => {
this.disho = data.json().results;
console.log(this.disho);
});
}
The above code ignore my where condition, and returns all the records.
However, the following code returns the right results when executed in terminal via cURL
curl -X GET \
-H "X-Parse-Application-Id: someKey" \
-H "X-Parse-REST-API-Key: someKey" \
-G \
--data-urlencode 'where={"estTime":"5min"}' \
https://parseapi.example.com/classes/Setto
Change { where : key } to { search : key }
Should work!
I think that there is a typo in your code. Single quotes are missing. You could try the following:
key.set('where', '{"estTime":"5min"}');

Parse: Creating a New Class Programmatically

Is it possible to create a new Class programmatically (i.e. not from the dashboard) via any of the API's or the Parse CLI?
The REST API appears to have functionality to fetch, modify and delete individual Schemas (classes) but not to add them. (https://parse.com/docs/rest/guide#schemas).
Hoping for something like the following:
curl -X ADD \
-H "X-Parse-Application-Id: XXXXXX" \
-H "X-Parse-Master-Key: XXXXXXXX" \
-H "Content-Type: application/json" \
https://api.parse.com/1/schemas/City
You seem to have skipped the part which deals with adding schema in the documentation. To create a new class, according to documentation, You use following method in cURL:
curl -X POST \
-H "X-Parse-Application-Id: Your APP Id" \
-H "X-Parse-Master-Key: Your master key" \
-H "Content-Type: application/json" \
-d '
{
"className": "Your Class name goes here",
"fields": {
"Your field name here": {
"type": "Your field's data type e.g. String, Int etc. Add multiple fields if you want"
}
}
}' \
https://api.parse.com/1/schemas/[Your class name]
Or in Python:
import json,httplib
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
connection.request('POST', '/1/schemas/Game', json.dumps({
"className":"[Your class name]","fields":{"Your field name":{"type":"your field's data type"} }
}), {
"X-Parse-Application-Id": "7Lo3U5Ei75dragCphTineRMoCfwD7UJjd1apkPKX",
"X-Parse-Master-Key": "ssOXw9z1ni1unx8tW5iuaHCmhIObOn4nSW9GHj5W",
"Content-Type": "application/json"
})
result = json.loads(connection.getresponse().read())
print result