Form Submit calling adapter - ibm-mobilefirst

I have a form that call a procedure onsubmit, this procedure parse the document and create a json object which is passed to an adapter. It seems when the onSubmit procedure end, the call to the adapter is killed and then the onFailure method of the adapter is called.
My question is how I can wait in my onSubmit procedure that the adapter is finished.
If I add a flag in the onSuccess and wait until the flag is set, I will not capture real failure. If I add a flag in the onFailure, as the onFailure is called because the process is killed, I will not be able to wait the end of the process.
It works if I add an alert after the call to the adapter in the onSubmit procedure and wait that the onSuccess is triggered...
Here some code:
function postCustomer(content) {
var invocationData = {
adapter : 'myAdapter',
procedure : 'postCustomerByContent',
parameters : [ content ]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : postCustomerSuccess,
onFailure : postCustomerFailure,
timeout: 30000
});
}
function postCustomerSuccess(result) {
var httpStatusCode = result.status;
if (200 == httpStatusCode) {
var invocationResult = result.invocationResult;
var isSuccessful = invocationResult.isSuccessful;
if (true == isSuccessful) {
WL.SimpleDialog.show('Title', "Success", [{text : 'OK'}]);
} else {
WL.SimpleDialog.show('Title', "Error. isSuccessful=" + isSuccessful, [{text : 'OK'}]);
}
} else {
WL.SimpleDialog.show('title', "Error. httpStatusCode=" + httpStatusCode, [{text : 'OK'}]);
}
}
function postCustomerFailure(result) {
WL.SimpleDialog.show('Title', "Failed:"+result, [{text : 'OK'}]);
}
function formSubmit() {
var application = document.forms["application"], initial = application["ibmerName"].value, email, name, organizationName = application['organizationName'].value, primaryContactName = application['primaryContactName'].value, primaryContactEmail = application['primaryContactEmail'].value, organizationAddress = application['organizationAddress'].value, primaryContactPhoneNumber = application['primaryContactPhoneNumber'].value, country = application['country'].value, organizationType = application['organizationType'].value;
if (initial == "xxx") {
email = "xxxxxxxxxxxxxxxxx";
name = "xxx";
} else if (initial == "yyy") {
email = "yyyyyyyy";
name = "yyyyyyyyyy";
} else {
email = "xxxxxxxxxxxxxxxxxx";
name = "xxxxxxxxxxxxxxxxx";
}
var content = '{"email":"' + email + '","name":"' + name
+ '","organizationName":"' + organizationName
+ '","primaryContactName":"' + primaryContactName
+ '","primaryContactEmail":"' + primaryContactEmail
+ '","organizationAddress":"' + organizationAddress
+ '","primaryContactPhoneNumber":"' + primaryContactPhoneNumber
+ '","country":"' + country + '","organizationType":"'
+ organizationType + '"}';
postCustomer(content);
alert(content);
}
Any idea?
Thx

is the page refreshing, if so, you have to do a return false at the end of your formSubmit function.

Related

Django channels without redis

I have a django app based on this tutorial that works perfectly. It uses Redis in the Channel layers
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [('127.0.0.1', 6379)],
},
},
}
The problem I have is that my web hosting provider will not allow Redis (unless I pay ££££).
Every example that I can find uses Redis in this role. Is there an alternative I could use?
there are a few options.
you can run your channel layer on a different service to were the main instance runs. AWS ElastiCache or many other redis hosts out there.
There is also a RabbitMQ channel layer but if your hosting provider charges a lot for reddis i expect they will also charge a lot for this ... https://github.com/CJWorkbench/channels_rabbitmq/
It turned out that channels is a non-starter on an affordable web-hosting platform. So I reverted to using Ajax and long polling. My application is based on this Django Tutorial.
models.py
class Message(models.Model):
room_name = models.CharField(null=False, blank=False, max_length=50)
sender = models.CharField(null=False, blank=False, max_length=50, default='Sender username')
datetime = models.DateTimeField(null=True, auto_now_add=True)
type = models.IntegerField(null=True, blank=True)
text = models.CharField(null=False, blank=False, max_length=250, default='message text')
context = models.TextField(null=True, blank=True)
urls.py
urlpatterns = [
path('<str:partner_pk>/check-message', views.CheckMessage.as_view(), name="check-message"),
path('<str:partner_pk>/send-message/<str:chat_text>', views.SendMessage.as_view(), name="send-message"),
]
views.py
class CheckMessage(View):
"""Duo check message."""
def get(self, request, partner_pk):
"""Render the GET request."""
pair, room_name = sort_pair(partner_pk, request.user.pk)
partner = User.objects.get(pk=partner_pk)
profile = get_object_or_404(Profile, user=request.user)
message = Message.objects.filter(room_name=room_name, sender=partner.username).earliest('datetime')
context = {'type': -1}
context = json.loads(message.context)
context['sender'] = message.sender
context['datetime'] = message.datetime
context['message_type'] = message.type
context['text'] = message.text
context['seat'] = profile.seat
message.delete()
return JsonResponse(context, safe=False)
class SendMessage(View):
def get(self, request, partner_pk, chat_text):
message_type = app.MESSAGE_TYPES['chat']
send_message(request, partner_pk, message_type, text=chat_text, context={})
return JsonResponse({}, safe=False)
chat.js
window.setInterval(checkMessage, 3000);
function checkMessage () {
$.ajax(
{
type:"GET",
url: "check-message",
cache: false,
success: function(message) {
processMessage(message);
}
}
)
}
// Take action when a message is received
function processMessage(context) {
switch (context.message_type) {
case 0:
sendMessage(context)
functionOne()
break;
case 1:
sendMessage(context)
functionTwo()
break;
case 2:
sendMessage(context)
functionThree()
break;
}
}
// Send a message to chat
function sendMessage (context) {
if (context.sender != username) {
var messageObject = {
'username': context.sender,
'text': context.text,
};
displayChat(context);
}
}
// Display a chat message in the chat box.
function displayChat(context) {
if (context.text !== '') {
var today = new Date();
var hours = pad(today.getHours(), 2)
var minutes = pad(today.getMinutes(), 2)
var seconds = pad(today.getSeconds(), 2)
var time = hours + ":" + minutes + ":" + seconds;
var chat_log = document.getElementById("chat-log");
chat_log.value += ('('+time+') '+context.sender + ': ' + context.text + '\n');
chat_log.scrollTop = chat_log.scrollHeight;
}
}
//pad string with leading zeros
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
// Call submit chat message if the user presses <return>.
document.querySelector('#chat-message-input').focus();
document.querySelector('#chat-message-input').onkeyup = function (e) {
if (e.keyCode === 13) { // enter, return
document.querySelector('#chat-message-submit').click();
}
};
// Submit the chat message if the user clicks on 'Send'.
document.querySelector('#chat-message-submit').onclick = function (e) {
var messageField = document.querySelector('#chat-message-input'), text = messageField.value, chat_log = document.getElementById("chat-log");
context = {sender: username, text: messageField.value}
displayChat(context)
sendChat(messageField.value)
chat_log.scrollTop = chat_log.scrollHeight;
messageField.value = '';
};
// Call the send-chat view
function sendChat(chat_text) {
$.ajax(
{
type:"GET",
url: "send-message/"+chat_text,
cache: false,
}
)
}

How to add onmessage handler for strophe muc plugin

How to add on-message handler for strophe MUC plugin.
Currently i added callback function for join action.
Gab.connection.muc.join(room_name+"#muc.162.242.222.249", login_id,
function(message){
You can check message types in your general message handler:
connection.addHandler(onMessage, null, 'message', null, null, null);
...
function onMessage(msg) {
var to = msg.getAttribute('to');
var from = msg.getAttribute('from');
var type = msg.getAttribute('type');
var elems = msg.getElementsByTagName('body');
if (type == "chat" && elems.length > 0) {
var body = elems[0];
console.log('CHAT: I got a message from ' + from + ': ' + Strophe.getText(body));
} else if (type == "groupchat" && elems.length > 0) {
var body = elems[0];
var room = Strophe.unescapeNode(Strophe.getNodeFromJid(from));
var nick = Strophe.getResourceFromJid(from);
console.log('GROUP CHAT: I got a message from ' + nick + ': ' + Strophe.getText(body) + ' in room: ' + room);
}
// we must return true to keep the handler alive.
// returning false would remove it after it finishes.
return true;
}

Mailgun - Attach a file in phantomjs

I am trying to make a application using phantomjs which requires mailgun service to send email. Since there is no official mailgun phantomjs library, I am facing some troubles with attaching files in the emails. The email is dispatched successfully but I dont see any attachment to it.
Here is the code:
function ObjToQs(obj) {
var str = "";
for (key in obj) {
str += key + '=' + obj[key] + '&';
}
str = str.slice(0, str.length - 1);
return str;
}=
var page = require('webpage').create(),
url = 'https://api.mailgun.net/v3/sandboxbxxxxxxxxxxxxxxxxxxxxxxxx.mailgun.org/messages',
data = {
from: "Ganesh <mail#gmail.com>",
to: "email#gmail.com",
subject: "subject!",
text: "Body",
attachment: '/path/test.txt'
};
console.log(ObjToQs(data));
page.customHeaders = {'Authorization': 'Basic ' + btoa('api:key-xxxxxxxx')};
page.open(url, 'post', ObjToQs(data), function (status) {
if (status !== 'success') {
console.log('FAIL to load the log');
console.log(status);
} else {
console.log('Log success');
var result = page.evaluate(function () {
return document.body.innerText;
});
console.log("log Result: " + result);
phantom.exit();
}
});
What should I do?
Thanks!
This will work for you -- it's a NodeJS lib for mailgun: https://www.npmjs.com/package/mailgun-js

WL.Server.getActiveUser returns Null

I need the ability to get a users login userid/password in a java adapter. After reading lots of articles, the best way seems to be to call
WL.Server.getActiveUser from a javascript function that gets called from the java adapter. So, I added a getIdentity function to the http adapter that authenticates our app. I have verified that getActiveUser works in the authentication function that the login pages calls...
When I call the getIdentity function, getActiveUser returns null using The same authentication realm. I have set the realm in the application_descriptor file. Not sure what else I have to do. Any ideas?
function performAuthentication(username, password) {
WL.Logger.info("In performAuthentication: username = " + username + " password = " + password + "Time = " + new Date(new Date().getTime()).toLocaleString());
var invocationData = {
adapter : 'BluePages',
procedure : 'authenticate',
parameters : [username, password]
};
var invocationResult = WL.Server.invokeProcedure(invocationData);
var fullName = invocationResult.result.fullName;
if (invocationResult.result.success == false) {
return {
authRequired: true,
loginPassed: false
};
}
else {
userIdentity = {
userId: username,
credentials: password,
displayName: username,
attributes: {
foo: "bar"
}
};
WL.Server.setActiveUser("AuthRealm", null);
WL.Server.setActiveUser("AuthRealm", userIdentity);
var activeUser = WL.Server.getActiveUser("AuthRealm");
WL.Logger.info("activeUser = " + activeUser);
if(activeUser && activeUser.userId == username){
WL.Logger.info("Active userId = " + activeUser.userId + " password = " + activeUser.credentials);
WL.Logger.info("User has been logged in!");
return {
loginPassed: true,
authRequired: false,
fullName: fullName,
result: invocationResult.result
};
}
else {
WL.Logger.info("Else Clause...");
if(activeUser != null)
WL.Server.setActiveUser("AuthRealm", null);
WL.Server.setActiveUser("AuthRealm", userIdentity);
}
return {
authRequired: false,
loginPassed: true,
fullName: fullName
};
}
}
function getIdentity() {
WL.Logger.info("AuthAdapter: In getIdentity: Time = " + new Date(new Date().getTime()).toLocaleString());
WL.Logger.info("AuthAdapter: userIdentity = " + userIdentity);
var activeUser = WL.Server.getActiveUser("AuthRealm");
WL.Logger.info("AuthAdapter: getIdentity: getActiveUser returned = " + activeUser);
if (activeUser) {
WL.Logger.info("AuthAdapter: getIdentity userId = " + activeUser.userId);
return {
userId: activeUser.userId,
credentials: activeUser.credentials,
};
}
}
There could be 2 reasons to get null when using WL.Server.getActiveUser:
1)If no realm is defined on the adapter, the method returns null (active user is unknown)
2)If a realm is defined on the adapter:
If there is no strong identity associated with the user (the user was authenticated in this session or in a previous session), the method returns null.
In your case you said the realm is exist so I suggest to try #2
You can find more information here:
https://www.ibm.com/support/knowledgecenter/SSZH4A_6.0.0/com.ibm.worklight.help.doc/apiref/r_method_wl_server_getactiveuser.html

Can I get the failed request id when PhantomJS get resource error?

I don't quite understand why PhantomJS only returns the url of request for onResourceError callback, while for the other two resource callbacks it returns the request id. That makes "finding which request did actually fail" really impossible if there is more than one request to the same url. Does anyone knows how to get the failed request id?
Actually, that's just old documentation. onResourceError has the id of a failed request.
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (request ID:' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
Why do you really need to request id ?
Since onResourceError was added in 1.9, some information may be missing.
A way to resolve your problem is to keep in an array all requested resourcessuach as in netsniff example.
Here is a very basic implementation :
var page = require('webpage').create(),
system = require('system');
if (system.args.length === 1) {
console.log('Usage: netsniff.js <some URL>');
phantom.exit(1);
} else {
page.address = system.args[1];
page.resources = [];
page.onLoadStarted = function () {
page.startTime = new Date();
};
page.onResourceRequested = function (req) {
page.resources[req.id] = {
request: req,
startReply: null,
endReply: null
};
};
page.onResourceReceived = function (res) {
if (res.stage === 'start') {
page.resources[res.id].startReply = res;
}
if (res.stage === 'end') {
page.resources[res.id].endReply = res;
}
};
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
page.resources.forEach(function (resource) {
var request = resource.request,
endReply = resource.endReply;
if (request && request.url === resourceError.url && !endReply) {
console.log('request id was :' + request.id);
}
})
};
page.open(page.address, function (status) {
var har;
if (status !== 'success') {
console.log('FAIL to load the address');
phantom.exit(1);
} else {
page.endTime = new Date();
page.title = page.evaluate(function () {
return document.title;
});
console.log(page.title);
phantom.exit();
}
});
}
onResourceError, you just need to find first/last/all recorded urls that match the error resource url.