Grails REST Client Plugin - PUT body content - rest

Documentation seems to be lacking on both the plugin side as well as the HTTPBuilder side of things. I'm trying to submit some json through the put method, but it keeps telling me that put() doesn't like the map I am feeding it.
Does anyone have an example of a PUT using the Grails REST Client plugin? Here is what I've tried:
withHttp(uri: "http://foo/doo/roo") {
def bodyContent = [
pano: jsonText
]
def json = put(body: bodyContent)
if (json.stat == 'ok') {
wsr.success = true
}
}
Error:
No signature of method: com.wbr.pano.PanService.put() is applicable for argument types: (java.util.LinkedHashMap) values: [[body:
{
"class":"com.wbr.platform.Pano",
"errorMessage":"null",
"imageSize":0,
"id":26,
"completed":"2011-03-20 3:50:27.257",
"downloading":"2011-03-20 3:49:12.269",
"processing":"2011-03-20 3:49:42.911",
"uploading":"2011-03-20 3:50:12.107"
}
]]

HTTPBuilder doesn't have a put method. Try changing withHttp to withRest so that your statements are executed with the RESTClient. Also, I think by default the body is encoded as URL encoded, so you might need to specify requestContentType: groovyx.net.http.ContentType.JSON as another parameter to your put.
import static groovyx.net.http.ContentType.*
withRest(uri: "http://foo/doo/roo") {
def bodyContent = [
pano: jsonText
]
def json = put(body: bodyContent, requestContentType: JSON)
if (json.status == 200) {
wsr.success = true
}
}

Related

How to send a POST request with Content-Type "application/x-www-form-urlencoded"

I am trying to send a POST request from my TornadoFX application to my nodejs server.
That's how i send my request to the server:
val api: Rest by inject()
api.baseURI = "http://localhost:5000/"
api.post("api/register", userModel) {
it.addHeader("Content-Type", "application/x-www-form-urlencoded")
}
My UserModel looks like this:
class UserModel : JsonModel {
val nameProperty = SimpleStringProperty("")
var name by nameProperty
val emailProperty = SimpleStringProperty("")
var email by emailProperty
override fun toJSON(json: JsonBuilder) {
with(json) {
add("name", name)
add("email", email)
}
}
}
Printing the request body on my node server i get following:
[Object: null prototype] {
'{"name":"Test","email":"test#test.org"}': ''
}
When i send a request via Postman i get the following body:
[Object: null prototype] {
name: 'Test',
email: 'test#test.org'
}
And that's what i'm trying to produce with TornadoFX without success.
I am grateful for any help!
You are correctly setting the Content-Type header, but you're pushing a JsonModel as your data, and consequently the framework will convert it to a JSON structure by calling toJSON() on it. The application/x-www-form-urlencoded content type expects an URL encoded piece of data, so you need to convert your data into an url encoded string. I suggest adding a function to your domain model like this:
fun toURLEncoded() =
"name=${name.urlEncoded}&email=${email.urlEncoded}".byteInputStream(StandardCharsets.UTF_8)
This example uses an extension function called urlEncoded to avoid clutter. You can define that extension function like this for example:
fun Any.urlEncoded(): String = URLEncoder.encode(toString(), "UTF-8")
Now you just have to call api.post("api/register", userModel.toURLEncoded()) and you should be good to go.

How to read query parameters in akka-http?

I know akka-http libraries marshal and unmarshal to class type while processing request.But now, I need to read request-parameters of GET request. I tried parameter() method and It is returning ParamDefAux type but i need those values as strings types
I check for answer at below questions.
How can I parse out get request parameters in spray-routing?
Query parameters for GET requests using Akka HTTP (formally known as Spray)
but can't do what i need.
Please tell me how can i extract query parameters from request. OR How can I extract required value from ParamDefAux
Request URL
http://host:port/path?key=authType&value=Basic345
Get method definition
val propName = parameter("key")
val propValue = parameter("value")
complete(persistanceMgr.deleteSetting(propName,propValue))
My method declarations
def deleteSetting(name:String,value:String): Future[String] = Future{
code...
}
For a request like http://host:port/path?key=authType&value=Basic345 try
path("path") {
get {
parameters('key.as[String], 'value.as[String]) { (key, value) =>
complete {
someFunction(key,value)
}
}
}
}
Even though being less explicit in the code, you can also extract all the query parameters at once from the context. You can use as follows:
// Previous part of the Akka HTTP routes ...
extract(_.request.uri.query()) { params =>
complete {
someFunction(key,value)
}
}
If you wish extract query parameters as one piece
extract(ctx => ctx.request.uri.queryString(charset = Charset.defaultCharset)) { queryParams =>
//useyourMethod()
}

Dynamically constructing closures from a map?

I'm trying to make a general method for sending SOAP requests and getting responses. I'm programming using Groovy and I'm using the wslite library to help me out with SOAP. Here's a sample snippet for making a SOAP request and getting a response:
#Grab('com.github.groovy-wslite:groovy-wslite:1.1.2')
import wslite.soap.*
SOAPClient client = new SOAPClient('http://www.dneonline.com/calculator.asmx')
def response = client.send(SOAPAction: 'http://tempuri.org/Add') {
body {
Add(xmlns: 'http://tempuri.org/') {
intA(x)
intB(y)
}
}
}
By general, I meant being able to dynamically create a SOAP request (given certain information such as the service/method name, the parameters contained in the method, etc.) and obtain the SOAP response. I'm thinking something like this:
#Grab('com.github.groovy-wslite:groovy-wslite:1.1.2')
import wslite.soap.*
def getResponse(String clientURL, String action, String service, String serviceNamespace, Map parameters, ...) {
SOAPClient client = new SOAPClient(clientURL)
def response = client.send(SOAPAction: action) {
body {
"$service"(xmlns: serviceNameSpace) {
...
}
}
}
}
My problem lies in constructing the closure for the request body. Like, in example, if my method received a service Add, a serviceNamespace http://tempuri.org/, and a parameter map like so: [intA: x, intB: y]... how do I merge all of these so that I can construct this kind of closure:
Add(xmlns: 'http://tempuri.org/') {
intA(x)
intB(y)
}
I'm pretty much a newbie to Groovy, so don't be too harsh. If there's a better way to implement this concept of a general method, I would gladly like to hear it. The concept is similar to this. But I'd rather play with Map than a String. I'm not using Grails, really. Just plain Groovy.
In short, cfrick is correct:
[intA: x, intB: y].each{fn,arg -> delegate."$fn"(arg) }
How does it work?
An easy way to see how this works is to simulate it with a fake client class:
groovy.util.NodeBuilder
class Client {
def send(String action, Closure closure) {
closure.delegate = new NodeBuilder()
closure()
}
}
def client = new Client()
def response = client.send('http://tempuri.org/Add') {
body {
Add(xmlns: 'http://tempuri.org/') {
intA(1)
intB(2)
}
}
}
assert response.Add[0].#xmlns == 'http://tempuri.org/'
assert response.Add.intA.text() == '1'
assert response.Add.intB.text() == '2'
In the example above, the response object is created by Groovy's NodeBuilder. It's just a quick way to prototype something that processes the closure passed to Client.send().
With this testable code I'll try what cfrick suggested and validate that it works:
def doIt(String action, String service, String serviceNamespace, Map params) {
def client = new Client()
client.send(action) {
body {
"$service"(xmlns: serviceNamespace) {
params.each { method, argument ->
delegate."$method"(argument)
}
}
}
}
}
response = doIt('http://tempuri.org/Add', 'Add', 'http://tempuri.org/', [intA: 1, intB: 2])
assert response.Add[0].#xmlns == 'http://tempuri.org/'
assert response.Add.intA.text() == '1'
assert response.Add.intB.text() == '2'
Request Body
In addition, you can factor out the process of creating the request body:
def getRequestBody(String service, String serviceNamespace, Map params) {
{ ->
"$service"(xmlns: serviceNamespace) {
params.each { method, argument ->
delegate."$method"(argument)
}
}
}
}
def doIt(String action, String service, String serviceNamespace, Map params) {
def client = new Client()
client.send(action) {
body(getRequestBody(service, serviceNamespace, params))
}
}

How can I parse out get request parameters in spray-routing?

This is what the section of code looks like
get{
respondWithMediaType(MediaTypes.`application/json`){
entity(as[HttpRequest]){
obj => complete{
println(obj)
"ok"
}
}
}
}~
I can map the request to a spray.http.HttpRequest object and I can extract the uri from this object but I imagine there is an easier way to parse out the parameters in a get request than doing it manually.
For example if my get request is
http://localhost:8080/url?id=23434&age=24
I want to be able to get id and age out of this request
Actually you can do this much much better. In routing there are two directives: parameter and parameters, I guess the difference is clear, you can also use some modifiers: ! and ?. In case of !, it means that this parameter must be provided or the request is going to be rejected and ? returns an option, so you can provide a default parameter in this case. Example:
val route: Route = {
(path("search") & get) {
parameter("q"!) { query =>
....
}
}
}
val route: Route = {
(path("search") & get) {
parameters("q"!, "filter" ? "all") { (query, filter) =>
...
}
}
}

Missing parameters with RESTful request when upgrading to Grails 2.3.0

I am using Grails with RESTful to develop my web application. Everything works fine, till I upgrade my application to Grails 2.3. Here is my UrlMappings:
I still send request, submit or do some other things normally, but in POST, PUT requests, the parameters are missing. Server just recognize only the parameters I put on the URL directly, but the remain I enclose in form or model when submit cannot be found in the "params" variable. He is my UrlMappings:
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?"{ constraints {} }
name apiSingle: "/api/$controller/$id"(parseRequest:true){
action = [GET: "show", PUT: "update", DELETE: "delete"]
constraints { id(matches:/\d+/) }
}
name apiCollection: "/api/$controller"(parseRequest:true){
action = [GET: "list", POST: "save"]
}
name api2: "/api/$controller/$action"(parseRequest:true)
name api3: "/api/$controller/$action/$id"(parseRequest:true)
"/"(view:"/welcome")
"500"(view:'/error')
}
}
I have read the latest document of Grails 2.3, at http://grails.org/doc/latest/guide/theWebLayer.html#restfulMappings
but I think it is not clear. I have tried it follow the documentation but have no result. And there are no any sample about using Grails 2.3 with RESTful for me to refer.
How can I make it work normally as before, and can access all parameter values in REST request? Thank you so much!
According to this http://grails.1312388.n4.nabble.com/Grails-2-3-and-parsing-json-td4649119.html parseRequest has no effect since Grails 2.3
If you use JSON as request body you can accees request params as request.JSON.paramName
As a workaround you can add a filter that will populate data from JSON to params:
class ParseRequestFilters {
def filters = {
remoteCalls(uri: "/remote/**") {
before = {
if (request.JSON) {
log.debug("Populating parsed json to params")
params << request.JSON
}
}
}
}
}
Adding on to Kipriz's answer and cdeszaq's comment, you can write a recursive method to inject nested params. Something along these lines:
public void processNestedKeys(Map requestMap, String key) {
if (getParameterValue(requestMap, key) instanceof JSONObject) {
String nestedPrefix = key + ".";
Map nestedMap = getParameterValue(requestMap, key)
for (Map.Entry<String, Object> entry : nestedMap.entrySet()) {
String newKey = nestedPrefix + entry.key;
requestMap.put(newKey, getParameterValue(nestedMap, entry.key))
processNestedKeys(requestMap, "${nestedPrefix + entry.key}");
}
}
}
public static Map populateParamsFromRequestJSON(def json) {
Map requestParameters = json as ConcurrentHashMap
for (Map.Entry<String, Object> entry : requestParameters.entrySet()) {
processNestedKeys(requestParameters, entry.key)
}
return requestParameters
}