Scala REST API call to a Java REST with FormParams - java

I wanted to know if you guys do know if it is possible in Scala to make a call to a Java REST client function which takes #FormParam params.
If my function in the Java client is this :
#Path("registerEmail")
#POST
public RegisterEmailResult doRegisterEmail(#FormParam("email") final String email, #FormParam("password") String password/* Some other params */) {
How can I pass some #FormParam params in Scala ? I tried this :
def registerEmail(registerEmail: RegisterEmail): Future[Boolean] =
post(
url("/theUrl/registerEmail"),
new Gson().toJson(registerEmail)
).map {
case data => true
}.recover {
case _ => false
}
The RegisterEmail model has all the field of the parameters of the Java function.
Did I miss something ? Otherwise I will have to do the Java function again with like #QueryParams, it seems to be maybe a better way.

It is simpler to understand your code if you include part of your imports as well. The url (which I assume is Play's play.api.libs.ws.WS.url(...)) can be utilised like this to pass form data:
WS.url("/theUrl/registerEmail")
.post(Map("email" -> Seq("someone#somewhere.com"),
"password" -> Seq("secretish")))
See https://www.playframework.com/documentation/2.3.x/ScalaWS for more details (specifically search for "Submitting form data")

Related

Nested attributes in Gatling Expression Language

I use Gatling Java to write a performance test.
I have a session variable 'VAR_X' with a value of 'Jerry'.
My code has a 'post()' method that sends a request. It uses a custom feeder to provide a body for the request.
public ChainBuilder post() {
List<String> requestBodyList = new ArrayList<String>();
Iterator<Map<String, Object>> feeder =requestBodyList.add(Collections.singletonMap("REQUEST_BODY", (Object) "my_config { x: #{VAR_X} }")).iterator();
return feed(feeder)
.exec(http("Post request"))
.post("x_resource/")
.body(StringBody("#{REQUEST_BODY}"))
}
Currently my code results in the request body to be "my_config { x: #{VAR_X} }".
I would like the value of session variable 'VAR_X' to get inserted into the request body, by using Gatling Expression Language (GEL).
The desired request body should be:
"my_config { x: Jerry }"
How can I change my code to achieve that?
That's not possible. Gatling Expression Language is intended as a simple solution for simple use cases.
For more complex use cases, you have to switch to using functions and the Session API.

Error tolerance of URI-encoded string syntax

I have picked up a legacy project and I am in the process of debugging something.
I have come across a custom JavaScript function (encodeJsonIntoString) which encode URI components for JavaScript object before sending over via AJAX.
The AJAX is nothing fancy:
$.ajax({
url: URL,
method: 'POST',
datatype : 'json',
data : encodeJsonIntoString(myObj),
success: ...
});
There is no custom processData or contentType set in the ajax call. What really puzzle me is why the previous developers didn't let $.ajax's data attribute to convert the JavaScript object automatically into a URI-encoded string or didn't even try using JQuery.param() to do it but to write the whole function themselves.
For a test, I have made a simple object to test the function encodeJsonIntoString:
var testDataA = {
list: [
{
lastname:"Smith",
firstname:"John"
},
{
lastname:"Black",
firstname:"Jack"
},
{
lastname:null,
firstname:"Mary"
}
]
};
After decoding URI components, the result of the function is:
list[0][lastname=Smith&list[0][firstname=John&
list[1][lastname=Black&list[1][firstname=Jack&
list[2][lastname=null&list[2][firstname=Mary
Notice there are lack of closing square brackets(]) in some places and it uses "null" for null values.
If I run JQuery.param() and decode it, I get this:
list[0][lastname]=Smith&list[0][firstname]=John&
list[1][lastname]=Black&list[1][firstname]=Jack&
list[2][lastname]=&list[2][firstname]=Mary
See the difference? But somehow the result of the function is accepted by the server(Java/Spring - #ModelAttribute) and read into the correct list structure.
I don't have access to the server side here, but I wonder if that array syntax is correctly acceptable or is it just "tolerated" by the server? Will the server see both versions of object in the same structure format?
I am tempted to just replace it with JQuery.param() to handle more robust input data in the future which may also accept special characters.

Proper json to back end post call

I'm having some troubles with different back-end processing of POST rest calls. I have two different objects which are updated through two different POST methods in my back-end. I catch the objects as a JsonNode, and in order to parse the attributes which I need to update, i create an iterator like so :
final Iterator<String> fieldNames = attributes.fieldNames();
The problem comes when I send my data from angular, in one case I need to explicitly send it like angular.toJson(data) in order to properly grab all the field names, and in the other case I just send the data (without the angular json conversion). Why is this behavior occurring ? Does this have to do with how I create the $http post call ? Here are the two different calls from angular:
$http.post(URL, angular.toJson(data)).success(function(data){
/*whatever*/ }).error(function(data) {
/*whatever*/ });
//Second call looks like this
var promise = $http({method: 'POST', url:URL, data:data, cache:'false'});
//this one i resolve using $q.all
I truncated the code to just the important stuff. My data is created like this currently(tried multiple ways in order to skip the need for toJson):
var data = "{\"Attribute1:\"+"\""+$scope.value1+"\","+
"\"Attribute2:\"+"\""+$scope.value2+"\"}";
How do I need to send the json data in order for it to correctly be converted to a JsonNode in my back-end, so I can properly iterate the fieldNames ?
I did manage to come to a common solution which consumes the json correctly in my back-end. I declared my json objects in angular like this :
$scope.dataToSend = {
"SomeAttribute" : "",
"SomeOtherAttribute" : ""
};
And then added my values like so :
$scope.dataTosend.SomeAttribute = someValue;
$scope.dataTosend.SomeOtherAttribute = someOtherValue;
No longer need to send the data with angular.toJson().

How to encode decode between js and java?

I am working on a project in that java script as front-end and java as back-end are used, my problem is that I want to pass some string using restangular calls to my back-end resources. If passing parameter have space between the string then I got 500 (Server Error) before reaching to back-end resource side.
Lets take example :
At Java Script : RESTangular call
var myRestCall= Restangular.all('myRoot/myMethod/'+myLocalPath+'/'+folderName);
restPSTFolders.getList().then(function(listPSTFolders){
//my stuff
});
At Java Resource :
#ApiOperation(value = "My Method",
notes = "Returns My Method list",
responseContainer = "List",
response = List.class)
#Path("/myMethod/{myLocalPath}/{folderName}")
#GET
#Transactional
#Timed
public List myMethod(#PathParam("myLocalPath") String myLocalPath, #PathParam("folderName") String sFolderName) {
//my stuff
}
In my example myLocalPath parameter can have spaces and special characters in the string as it can be any :
C:\MY DRIVE\My Path One\My Path
D:\My favorite
To pass this to back-end class from RESTangular call, I need to replace all spaces with some character, it work for me, but I am not thinking its a good way to encode the special character and space with any character because the replacing character can also be a part of existing path then at back-end on again replacing the character, might change the path.
EDIT : If I passed the parameter as json object:
var parameterJsonPath = {};
parameterJsonPath={"myLocalPath": pathValue};
var myRestCall= Restangular.all('myRoot/myMethod/'+parameterJsonPath+'/'+folderName);
Does not make any sense as I got : ../myRoot/myMethod/%5Bobject%20Object%5D Failed to load resource: the server responded with a status of 500 (Server Error)
And making the parameterJsonPath to JSON.stringify(parameterJsonPath); will pass this as string that of no use for me.
Thus in all, is there any good way to encode the special character of string in js, so at back-end side I could decode that string using same key that were used while encoding?

Java Play 2 - Function as a parameter in scala

I have problems to write reusable code in scala.
If i have something like
#helper.form(action = routes.Guides.addComment(category,title)) {
Is there a way to replace it with a variable?
pseudo code
#(func : Function)
#helper.form(action = func) {
Edit:
Oh.... now it's kinda obvious. The function itself should return a string , so I guess i can just say something like this
#(func :String)
..
.
return ok (form.render(routes.Guides.test()))
Testing it now
May I suggest an alternative? Use Call directly.
#(route: Call)
#helper.form(action = route) {
...
}
In Scala, you could even pass only a part of the route and fill the rest from the controller (very useful when you're using pagination).
figured it out.
with
routes.Guides.test().url
you get the url and then you can use it as a parameter
for example
#guidesComment((routes.Guides.addComment(ug.category,ug.title)).url)
guidesComment looks like this
#(func: String)
Then use it like this
<form action="#func" method="POST">

Categories

Resources