Adapter request does not return expected data - ibm-mobilefirst

My worklight app has a page to post some values to a remote server. This is done using an adapter which calls the url to post. The client javascript is:
var invocationData = {
adapter : 'StoryAdaptor',
procedure : 'postStoryDetails',
parameters : [ storyParameters ]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : function(data) {
alert("return message: "+JSON.stringify(data))
},
onFailure : function(data) {
alert("Couldn't save Story");
}
});
The adapter method is
function postStoryDetails(storyParameters){
var input = {
method : 'post',
returnedContentType : 'json',
path : "/postStory.json",
parameters : storyParameters
};
var authResult = WL.Server.invokeHttp(input);
}
The remote application is a java Spring application which takes the parameters and on successful save, returns just a string "success".
#RequestMapping(value = { "/postStory" }, method = RequestMethod.POST)
public String postStory(HttpServletRequest request,HttpServletResponse response){
Story story = new Story();
story.setTitle(request.getParameter("title"));
.
.
.
boolean status = storyService.saveStory(story);
if(status ){
return "success";
}
return "failed";
}
I am not getting the "success" message in worklght. Instead, each time, the alert is printing
return message: {"status":200,"invocationContext":null,"invocationResult":{"isSuccessful":true}}
Why I am not getting my returned message?

Try returning like the following:
return {
result: "success";
}
For Worklight 6.2, see Using Java in Adapters, slide #11
For MobileFirst Platform 3.2, see Using Java in Adapters, section "Invoking custom Java classes from the adapter"

Related

Titanium open remote data in url

I'm parsing remote data in to my app and uses it through arguments. One of the data types is a url adresse i want to open in the url. I have an idea that I have to open it with the openURL function but I can't seem to get it to work. Anyone have a working example?
You have to utilize in-built HttpClient
var url = "http://www.you_remote_url.com";
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("Received text: " + this.responseText);
alert('success');
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert('error');
},
timeout : 5000 // in milliseconds
});
// Prepare the connection.
client.open("GET", url);
// Send the request.
client.send();

MobileFirst 7.0 combining Authentication and Java SQL Adapter fails

Im trying to combine Java UserAdapter and Adapter-based authentication
I want to get the users list after authenticated, but it fails
On server-side, Adapter-based authentication, AuthenticationAdapter-impl.js
function onAuthRequired(headers, errorMessage) {
errorMessage = errorMessage ? errorMessage : null;
return {
authRequired: true,
errorMessage: errorMessage
};
}
function submitAuthentication(username, password){
if (username==="admin" && password === "admin"){
var userIdentity = {
userId: username,
displayName: username,
attributes: {
foo: "bar"
}
};
WL.Server.setActiveUser("AdapterAuthRealm", userIdentity);
return {
authRequired: false
};
}
return onAuthRequired(null, "Invalid login credentials");
}
function listUsers() {
var resourceRequest = new WLResourceRequest("/adapters/UserAdapter/", WLResourceRequest.GET);
return resourceRequest.send();
}
function onLogout() {
WL.Server.setActiveUser("AdapterAuthRealm", null);
WL.Logger.debug("Logged out");
}
And on client-side,
function listUsers(){
busyIndicator.show();
var invocationData = {
adapter : "AuthenticationAdapter",
procedure: "listUsers",
parameters: []
};
WL.Client.invokeProcedure(invocationData, {
onSuccess: listUsersSuccess,
onFailure: listUsersFailure
});
}
function listUsersSuccess(result){
WL.Logger.debug("Feed retrieve success");
busyIndicator.hide();
WL.Logger.debug(JSON.stringify(result));
if (result.responseJSON.length > 0){
displayUsers(result.responseJSON);
} else {
listUsersFailure();
}
}
function listUsersFailure(result){
WL.Logger.error("Feed retrieve failure");
busyIndicator.hide();
WL.SimpleDialog.show("Banking Application", "Service not available. Try again later.", [
{
text : 'Reload',
handler : WL.Client.reloadApp
},
{
text: 'Close',
handler : function() {}
}
]);
}
It returns onFailure response
WLResourceRequest is a client side API so you CAN NOT use it on an adapter since the adapter runs on the server.
You should update your listUsers function (client side) as follows:
function listUsers(){
busyIndicator.show();
var resourceRequest = new WLResourceRequest("/adapters/UserAdapter/", WLResourceRequest.GET);
resourceRequest.send().then(listUsersSuccess).fail(listUsersFailure);
}
Update
You can protect your Java Adapter methods by using the #OAuthSecurity annotation.
UserAdapter.java
#GET
#Path("/protectePath")
#OAuthSecurity(scope="YourRealm")
public String myProtectedMethod() {
// your code here
return "your-response";
}

how to submit json file in sencha touch in http post multipart?

I want to submit json file form sencha touch to my tomcat server using http post multipart but i don't know how to do ?
can any one give me some idea or example.
Thanks
you can do this using jQuery.
var request = new FormData();
$.each(context.prototype.fileData, function(i, obj) { request.append(i, obj.value.files[0]); });
request.append('action', 'upload');
request.append('id', response.obj.id);
$.ajax({
type : 'POST',
url : context.controller,
data : request,
processData : false,
contentType : false,
success : function(r) {
console.log(r);
//if (errors != null) { } else context.close();
},
error : function(r) { alert('jQuery Error'); }
});

How to get the response after a POST request in CasperJS

I have this very simple code to read the response from a server endpoint after a post request. Actually I'm saving a data to a database and wait for a response before going to next step
casper.open('http://example.com/ajax.php, {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
});
on ajax.php file I'm trying to echo the POST request in a simple way.
this will let me know easily if I'm getting the right response from the server.
echo json_encode($_POST);
I tried these snippets but I'm unable to get the response.
casper.on('page.resource.received', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('http.status.200', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('resource.received', function(resp) {
this.echo(JSON.stringify(resp, null, 4));
});
I've been facing the same problem POSTing a query to ElasticSearch and I could not retrieve the results.
As far as I can understand if you want to retrieve the data echoed by your script the solution could be this:
this.echo(this.page.content);
or
this.echo(this.page.plainText);
in your function.
For example (my case with ElasticSearch):
/*
* SOME VAR DEFINITIONS HERE
*/
casper.start();
casper.then( function() {
// the next var is very specific to ElasticSearch
var elasticQuery = JSON.stringify (
{
'size' : 20,
'query' : {
'filtered' : {
'filter' : { 'term' : { 'locked' : false } }
}
},
'sort': { 'lastScrapeTime': { 'order': 'asc' } }
}
);
var elasticRequest = {
method: 'POST',
data: elasticQuery
}
this.thenOpen( <<YOUR URL>>, elasticRequest, function (response) {
// dump response header
require('utils').dump(response);
// echo response body
this.echo(this.page.content);
// echo response body with no tags added (useful for JSON)
this.echo(this.page.plainText);
});
}
);
casper.run();
As Roberto points out. You can use this.page.content to show the response. But you need to add the function(response) in your script. For example:
casper.open('http://example.com/ajax.php', {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
}, function(response){
if(response.status == 200){
require('utils').dump(this.page.content);
}
});
If you want to unit test a REST API, CasperJS is not necessarily the right tool.
CasperJS allows to observe a web browser which is running a web page.
So a more typical approach would be to use CasperJS to load a page that would call your REST API and you would assert the page behavior is correct (assuming the page would make something observable according the AJAX call response).

Variable visibility in callbacks functions

I did this function for get results of a query directly in an useful datastructure. The problem is the follow: in the first console.log() call , inside the callback function, the stored_data var contains the exact results, in the second console.log() call the stored_data variable looks like not initialized. Suggestions??
Below the code:
function dojo_query_mysql(query_string) {
//The parameters to pass to xhrPost, the message, and the url to send it to
//Also, how to handle the return and callbacks.
var stored_data;
var raw_data = new Object;
var xhrArgs = {
url: "query.php",
postData: query_string,
handleAs: "text",
load: function(data) {
raw_data = dojo.fromJson(data);
stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
console.log(stored_data);
},
error: function(error) {
//We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
//docs server.
//stored_data = error;
}
}
//Call the asynchronous xhrPost
var deferred = dojo.xhrPost(xhrArgs);
console.log(stored_data);
return stored_data;
}
I have just remembered that the function doesn't wait the end of the callback execution, for wait the callback end just do a little change to the code:
var xhrArgs = {
url: "query.php",
sync: true, // THIS IS FORCE THE SYNCRONIZATION BETWEEN THE CALLBACK AND THE CODE
postData: query_string,
handleAs: "text",
load: function(data) {
raw_data = dojo.fromJson(data);
stored_data = new dojo.data.ItemFileReadStore({data: raw_data});
console.log(stored_data);
},
error: function(error) {
//We'll 404 in the demo, but that's okay. We don't have a 'postIt' service on the
//docs server.
//stored_data = error;
}
}