Async JavaScript connection with Java and passing parameters - java

I am sorry, I know the question is pretty stupid, but I am pretty new at Java, I've been working a lot with .NET.
With .NET I was using the following function to gather data and receive response from another page:
$.ajaxSetup({
global: false,
timeout: 60000,
type: "POST"
});
$.getJSON("Async/GetRegionalData",
{
requestedFunction: "getData",
id: 1
},
function (data) {
if (data != null) {
if (!data.ErrorCode == "0") {
}
else {
//function goes here
}
}
}
});
My question is this: How can I achieve the same thing with Java file as a server side?
Any links to relative topics would be of help.
How to get the parameters in the url that is requested? Anything connected with this topic is helpful. I did some research, but I didn't find much regarding this topic. Thank you in advance.

Related

nodejs and java api performance comparison

I have done a performance test of an REST API which is inserting data into MongoDB and also developed two applications using Java and Nodejs Express.
For testing, I have used JMeter which is invoking API 10 times (10 users) and realised that Java gave me consistent performance but Nodejs didn't.
Sometimes Nodejs app is taking more than 2ms to insert simple records into MongoDB.
As I have heard that Nodejs is faster for IO applications but did not find it.
Can someone tell me why I am not getting that performance or is my understanding or result I got is correct?
note: I am Java expert, learning Nodejs.
UPDATE :
I have created rest api which will insert records in mongodb and I am using mongoose to insert it . below is my code -
router.post("/", (req, res, next) => {
const order = new Order({
_id: new mongoose.Types.ObjectId(),
email: req.body.name,
uid: req.body.uid,
});
console.log(order);
order.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Order is successfully added",
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});

HTML5 Android Notification, (Intel XDK?)

(When I say "App" I am only talking about Android, I'm not gonna even try to deal with Apple)
So I have a website that I'd like to develop an Android app for. All I need it to do is show the website(it'll change some styling if being accessed from the app), which I can do just fine.
I use Intel XDK, which works great. But the notification options it offers seems to be just mass-notification stuff, not individualized.
All I want to do is be able to tell users when they get a notification from my website(like a message from another user).
I've looked all over the place for hours and hours and can't find anything useful. There are a ton of extremely complicated Java codes and tutorials, but I don't even know Java. I'm solely a web developer and all I want is an app that makes it easier for users to check the website.
I'm hoping there is some Java file out there that I can send data to somehow that will allow me to create and delete push notifications on Android systems. Maybe a HTML5 library or JS function, I dunno.
I simply can't seem to implement it myself, and I'm definitely not going to learn an entire dying language just for one basic thing that should be simple to do. Anything you guys can provide would be greatly appreciated. Optimally I would like to get a Java file I can download and put into my app that gives a notification, then I can edit it to say what I need it to or whatever(I also would really like a way to make the notification go away[in case the user sees it on another device before seeing it on the phone] ). I would also need to know how to call onto this Java file, make it check for notifications on the server or whatever.
I know this is all very nooby stuff, but I run an independent website and simply don't have the time to learn all this stuff when my needs are so basic. Thanks in advance.
You can use appMobi for push messaging, see documentation at http://docs.appmobi.com/index.php/push-messages/pushjsapi/. You can setup your appMobi account in the Services tab of the Intel XDK.
//Check if user is registered
var onDeviceReady=function() {
//See if the push user exists already
//You can send any unique user id and password.
AppMobi.notification.checkPushUser(AppMobi.device.uuid, AppMobi.device.uuid);
};
document.addEventListener("appMobi.device.ready",onDeviceReady,false);
//if user is not registered, register them
var isUserAdded = false;
var notificationsRegistered=function(event) {
if(event.success === false) {
if (!isUserAdded) {
isUserAdded= true;
AppMobi.notification.addPushUser(AppMobi.device.uuid,
AppMobi.device.uuid,
'no#email.com');
return;
}
AppMobi.notification.alert("Notifications Failed: " + event.message,
"My Message","OK");
return;
}
var msg = event.message || 'success';
AppMobi.notification.alert("Notifications Enabled: " + msg,
"My Message","OK");
};
document.addEventListener("appMobi.notification.push.enable",
notificationsRegistered,false);
//when push message event is found get notification
var receivedPush = function(){
var myNotifications=AppMobi.notification.getNotificationList();
//It may contain more than one message, so iterate over them
var len=myNotifications.length;
if(len > 0) {
for(i=0; i < len; i++) {
msgObj=AppMobi.notification.getNotificationData(myNotifications[i]);
try{
if(typeof msgObj == "object" && msgObj.id == myNotifications[i]){
AppMobi.notification.alert(msgObj.msg + "\n" + msgObj.data
+ "\n" + msgObj.userkey,"pushMobi Message","OK");
//Always delete messages after they are shown
AppMobi.notification.deletePushNotifications(msgObj.id);
return;
}
AppMobi.notification.alert("Invalid Message Object: " + i,
"My Message","OK");
}catch(e){
AppMobi.notification.alert("Caught Exception For: " + msgObj.id,
"My Message","OK");
AppMobi.notification.deletePushNotifications(msgObj.id);
}
}
}
};
document.addEventListener("appMobi.notification.push.receive", receivedPush, false);
//send a push notification from your website
AppMobi.notification.sendPushNotification(myAppMobiUserID,"new website blog posted!",{});
document.addEventListener("appMobi.notification.push.send",updateNotificationEvent,false);
var updateNotificationEvent=function(event)
{
if(event.success==false)
{
alert("error: " + event.message)
}
else
{
alert("success");
}
}
You can also use Parse.com APIs but I don't believe the subscribe to channel JavaScript API is fully flushed out last I checked, see https://www.parse.com/docs/push_guide#top/JavaScript.
Parse.initialize("YOUR KEY", "HERE");
// Save the current Installation to Parse.
ParseInstallation.getCurrentInstallation().saveInBackground();
You can then send push notifications through the Web Console, or on your website using:
//The following code will push the alert to the "Winterhawks" and "Oil Kings" channels.
Parse.Push.send({
channels: [ "Winterhawks", "Oil Kings" ],
data: {
alert: "The Winterhawks won against the Oil Kings!"
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
Subscribe to channels is not yet implemented for JavaScript as far as I know so you'll have to use REST or native APIs.

PHP Long Polling Issues

I have a web application which serves as the Admin Panel. It has a live chat option which connects with writers(employees) on the other end. The web application uses the following PHP code to check for online writers.
$q = 0;
$lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
while ($q<5){
sleep(3);
$wresult = $db->query("SELECT writer_alias FROM tblwriter WHERE writer_isactive=1 AND (UNIX_TIMESTAMP(NOW())-last_activity)<10");
if ($wresult->num_rows){ break; }
++$q;
}
if ($wresult->num_rows){
while ($row = $wresult->fetch_object()){ $writers[] = $row; }
$wresult->free();
}
echo json_encode(
array(
"writers" => $writers,
"now" => time()
)
);
On the application the following javascript code handles the PHP response and calls ajax again to complete the loop.
function UpdateCHAT(){
$.ajax({
type: "POST",
url: "liveserver.php",
data: {update:"1",timestamp:lastime},
success:
function(data1){
if (data1 == null){
$(".onlinechat i").removeClass("icon-white");
}else{
lastime = user_signin = Number(data1.now);
if (!data1.writers.length){
$(".onlinechat i").removeClass("icon-white");
}else{
$(".onlinechat i").removeClass("icon-white");
$.each(data1.writers,function(j) {
$("#writer_"+data1.writers[j].writer_alias).find("i").addClass("icon-white");
});
}
}
},
dataType: "json",
timeout: 60000,
complete:
function(){
UpdateCHAT();
}
}
);
}
Everything is working just fine except the fact that I cannot think of a way to know for offline writers since the PHP code is designed to check for the online writers, but this means if a writer is online once, he will remain online (on the application) until the PHP code dies and return empty writers.
Hope I am able to explain my point. This question is more to do with idea rather than piece of code. Any input is appreciated.
Thanks.
Make the PHP code always return after some time (like 2 minutes) with an empty result set (ie. no new chat lines).
JS will then do a new request immediately. If it doesn't, well, then the user is offline. Keep a last_request timestamp, if it's older than 2+e minutes the user is offline.
You could try to detect when the connection closes in PHP. Set ignore_user_abort(true) so you are in control of when your script dies. Then use connection_aborted() to check if the client closed. If he did you know he left.
A potential problem occurs if the user has two windows open: a close on one doesn't mean he left, but this may turn out to be acceptable; the user will blip for just a while.
Another solution is to use a separate ping request that just tells you "yep, I'm still here". If you haven't gotten one of those in a while the user is probably offline.

Response message on ajax file upload in java

I need to upload multiple files from jsp. I am using $ajaxFileUPload.js to take the file to server side. I am doing my file size validation in server side for each file. I need a message on validating the file, where i face a problem. I am not able to show that message. Could someone help me in this please?
I have not used the plugin but what I have done previously in similar situation is send different markers back to the client side like for an upload the exceeds the file limit size, you can start the response back with something like 'ERROR:' and then look for this marker in the function getting the response back and then branch to a different logic. You obviously have to parse the response and look for the marker.
Looking quickly at the plugin in Github, it looks like the usage is
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
So what I think you can do is in the onComplete function something like
if (response.search("ERROR:") != -1){
//error condition
//add your msg for the front end here
} else {
//non error condition, continue with your regular flow
}
Does this make sense and relate to what you are trying to do?

Java: Oauth 2.0 How can I use Google API RefreshTokens to avoid requesting access every time my app launches?

There is a lot of sample code for the google API showing how to Get an authorization token and use it, but I cannot find any sample code that shows you how to use the Oauth 2.0 GoogleAccessProtectedResource.refreshToken() method in the java client to get a new authorization token in in Java. Google search turns up nothing, and I can only find a C# example on Stackoverflow. If you could point me to a bit of sample code in Java showing how this is done that would be great. The platform I am working on in Android. An example of the model of OAuth 2.0 I would like to use is here: http://blog.doityourselfandroid.com/2011/08/06/oauth-2-0-flow-android/
Thanks a lot
Answering my own question here. It turned out to be quite straight forward, by calling GoogleAccessProtectedResource.refreshToken() the accesstoken is refreshed inside the class, it can be read and reused as needed through its getter.
You would have to catch 401(unauthorized) errors. After this do something like this.
accountManager.invalidateAuthToken(accessProtectedResource.getAccessToken());
accessProtectedResource.setAccessToken(null);
After this simply get back the token. This time user will not have to authorize access again.
accountManager.manager.getAuthToken(account, AUTH_TOKEN_TYPE, true,
new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, REQUEST_AUTHENTICATE);
} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
accessProtectedResource.setAccessToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
onAuthToken();
}
} catch (Exception e) {
handleException(e);
}
}
}, null);
Refer the task sample for reference and the corresponding article.

Categories

Resources