MobileFirst - Answering a call to a WS (JAX-RS) - ibm-mobilefirst

I have a java adapter (JAX-RS) that returns a POJO, one of the attributes is called validateUser and is a boolean value. I want to get the value of this boolean when called from main.js
It should work like this (main.js):
onGetLoginSuccess function (response)
busy.hide ();
alert ("validate:" + response ["validateUser"]);
As I can get the value in the variable response, the validateUser attribute my POJO.
Thank you for your attention

You can use alert(response.responseJSON.validateUser);
In general to examine the structure of "response" you could do something like: alert(JSON.stringify(response)); It could help you to understand which fields are available and how can you find this validateUser.
It is also important to make sure that your JAX-RS adapter returns JSON content type. Make sure that you have the annotation: #Produces("applicaion/json") in your JAX-RS method that returns this POJO

Related

How to send custom http response code back from spring cloud functions in gcp?

We are using the new gcp cloud functions using Java / Kotlin.
As in the current reference implementations, we are returning org.springframework.messaging.support.GenericMessage objects.
So our code looks like this (Kotlin):
fun generatePdfInBase64(message: Message<Map<String, Any>>): Message<*> {
val document = process(message)
val encoded = Base64.getEncoder().encodeToString(document.document)
return GenericMessage(encoded)
}
We were not able to find any way to include a custom http response code to our message, e.g. 201 or something. The function only responds 200 in case of no exception or 500.
Does someone know of a way to do this?
Best wishes
Andy
As it is mentioned at the official documentation, the HttpResponse class has a method called setStatusCode where you are able to set the number of the status as your convenience
For example:
switch (request.getMethod()) {
case "GET":
response.setStatusCode(HttpURLConnection.HTTP_OK);
writer.write("Hello world!");
break;
On the other hand the constructor of the GenericMessage receives as parameter a payload, therefore I think you can create a string with a json format and use the constructor for create your GenericMessage instance with the status response you need.
If you want to know more about the statuds codes take a look at this document.

Ktor returns 415 from endpoints where receive() is used with ContentNegotiation

I have parameter classes with the #Searializable annotation:
#Serializable
data class ShowPostURL(
val date: String,
val titleSlug: String,
override val redirectTo: String? = null
)
and no matter what I do call.receive() won't work. I'm getting HTTP 415 errors and Ktor doesn't log anything. I've added the serialization support as well:
install(ContentNegotiation) {
json()
}
How do I fix this? This is how I'm trying to use it:
accept(ContentType.Any) {
get("/foo/{date}/{titleSlug}") {
val input = call.receive(ShowPostURL::class)
call.respondText("foo")
}
}
If I do a trace I can see that my route is matched, but it can't receive the parameters. Is this json() setup is supposed to work when I'm deserializing from url parameters like this?
Firstly, ContentNegotiation feature works only for receiving custom objects from the payload of POST, PUT and PATCH requests:
POST, PUT and PATCH requests have an associated request body (the payload). That payload is usually encoded.
In order to receive custom objects from the payload, you have to use the ContentNegotiation feature. This is useful for example to receive and send JSON payloads in REST APIs.
When receiving, the Content-Type of the request will be used to determine which ContentConverter will be used to process that request
Secondly, there are three out of the box ContentConverter available:
GsonConverter, JacksonConverter and SerializationConverter.
Each of these converters has its own configuration function: gson, jackson and serialization respectively. You use json configuration function which is most likely is not appropriate for the configuration of ContentNegotiation.
To solve your problem you can access URL parameters by referring them with call.parameters and manually create ShowPostURL object. Then serialize it with the kotlinx.serialization framework if needed.
Also, you can write your own ContentConverter to implement custom logic for receiving typed objects.

Implicit cast operator in ActionResult<bool> not working

I am following this guide to build my controllers. I do the following.
This is my controller:
// GET api/sth/{sthId}/isValid
[HttpGet("{sthId: int}/isValid")]
[ProducesResponseType(StatusCodes.Status200OK)]
[MyAuthorizeFilter]
public ActionResult<bool> Whatever(int sthId)
{
return this.myService.Whatever(sthId);
}
Theoretically, this should be converted to an Ok() ActionResult. However, If I write the following unit test:
[Fact]
public void Whatever()
{
this.myServiceMock.Setup(x => x.Whatever(It.IsAny<int>())).Returns(true);
-> I DEBUG HERE -> var result = this.myController.Whatever(1);
Assert.IsType<OkObjectResult>(result);
Assert.True((bool)result.Value);
}
I see that my result is an ActionResult<bool> indeed, whose Value is true as expected, but result.Result is null. So: no Ok action result whatsoever.
What am I missing? Do I have to write explicitly the return Ok() to get it? With the sentence
Implicit cast operators support the conversion of both T and ActionResult to ActionResult<T>. T converts to ObjectResult, which means return new ObjectResult(T); is simplified to return T;.
in the documentation I thought it was not necessary...?
The ActionResult<TValue> class:
wraps either an[sic] TValue instance or an ActionResult.
See also the source, its constructors assign either Value or Result, never both.
The MVC pipeline will assign a success status code to the response if no status code was explicitly set. But I can't find documentation for that claim.
This means the response as obtained in this test won't have a status code or OkActionResult anywhere. You can convert it to an ObjectResult, but that won't have a status code.
If you use something like swagger you will indeed get an OK from the server.
This happens to you because you dont perform an http request you simple call a method(your controller method) and you get a return type. You dont create a web server or something so no http status code is generated by .net core.
If you want to get status codes you should write test using http requests. Generally you could look up something like postman to perform your testing.

wcf message response parameter

I've read this example http://msdn.microsoft.com/en-us/library/ee476510.aspx about dynamic responses in wcf.
The sample on the bottom fit my goal pretty well. This is what i did:
[OperationContract]
[WebGet(UriTemplate = "/salaries({queryString})")]
Message GetSalaryByQuery(string queryString);
and my GetSalaryByQuery-Method:
public Message GetSalaryByQuery(string querystring)
{
if (WebOperationContext.Current.IncomingRequest.Accept == "application/json")
return WebOperationContext.Current.CreateJsonResponse<Result>(Salary.GetSalaryByQueryJson(querystring));
else
return WebOperationContext.Current.CreateAtom10Response(Salary.GetSalaryByQuery(querystring));
}
It is pretty similiar to the example i found.
But its not working however. It says that there is another parameter besides the message. I googled the message-class and it seems to me that its not possible to add an parameter to a message-response.
Is there a way to pass a parameter with the request and get a response with a message object?
Is there another way to get the dynamic response?
Thanks in advance.
I got it to work. I just deleted the Metadata-Enpoint and the behavior. My Webservice provides metadata on its own and therefore doesnt need to have the mex-Metadata defined.

Unable to add body to RestSharp RestRequest using enums

I am using RestSharp in ASP .NET MVC 2 project. Trying to create RestRequest (using POST method) and add two enum values (my enum type -- OrderStatusFlags) to request body -- using build-in RestSharp XmlSerializer:
var request = new RestRequest("orders/{vendorID}/{number}", Method.POST);
request.AddBody(previousOrderStatus);
request.AddBody(newOrderStatus);
But after calling AddBody method in request parameters can see only empty but no value. And while calling MVC action method an error occurs:
The parameters dictionary contains a null entry for parameter 'previousStatus' of non-nullable type 'OrderStatusFlags' for method 'RestResponse PostOrderStatus(Int32, System.String, OrderStatusFlags, OrderStatusFlags)' in 'OrdersResourceEndpoint'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
Enum look like this:
public enum OrderStatusFlags : long
{
Pending,
Confirmed,
...
}
Does anybody occurs a similiar situation?
A couple issues here. First, you can only call AddBody() once or the last call will take precedence. AddBody() is also only for sending XML as the request body. What is the required XML schema that you need to send to that URL? Can you post some sample XML that you're trying to generate?
I think more likely you actually want to use AddParameter() to add some POST parameters since that is far more common than XML request bodies.