I am trying to use Javascript websockets to connect to a Java servlet, but the onError function is always being called, and is not providing much information. My javascript:
var webSocket = new WebSocket('ws://localhost:8080/test');
webSocket.onerror = function(event) {
onError(event);
};
webSocket.onclose = function(event) {
onClose(event);
};
webSocket.onopen = function(event) {
onOpen(event);
};
webSocket.onmessage = function(event) {
onMessage(event);
};
function onClose(event) {
var code = event.code;
var reason = event.reason;
var wasClean = event.wasClean;
alert(code + "; " + reason + "; " + wasClean);
}
function onMessage(event) {
//do stuff
}
function onOpen(event) {
webSocket.send('opening socket');
}
function onError(event) {
alert(event.message);
}
For my servlet, I have
#ServerEndpoint("/test")
public class TranscoderSNSServlet extends HttpServlet {
...
}
The only useful error codes I've been able to find are that event.code = 1006, event.wasClean = false. The browser I am using definitely supports websockets. I am trying to run this on ElasticBeanstalk. Any help is appreciated
Related
I'm trying to update an HTML5 table in real-time with some data from the database. Here is my code:
HTML page:
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("[some address]/api/sse");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("placeholder").innerHTML=table;
};
}
else {
[erro message]
}
</script>
And my Java Restful service:
#Path("/sse")
public class SSEResource {
#Context
private UriInfo context;
public SSEResource() {
}
#GET
#Produces(SseFeature.SERVER_SENT_EVENTS)
public String getServerSentEvents() throws Exception {
SomeObject o = new SomeObject();
final String myString = o.someQuery().getEntity().toString();
return "data: " + myString + "\n\n";
}
}
This someQuery() method queries from database and returns what I want to put on my table. Everythings looks great. But I want to know if it's right or wrong, because if I put some log on someQuery() method, I see that every 3 seconds the query is executed. This may cause heavy duty, right? Is this normal or is my code wrong?
My java-script function with ajax which has to be moved in to a java class:-
<script type="text/javascript">
$(document).ready(function(){
var polyLat = new Array();
polyLat[0] = 10.194027;
polyLat[1] = 10.226975;
polyLat[2] = 10.059987;
polyLat[3] = 10.002248;
polyLat[4] = 9.854925;
polyLat[5] = 9.835443;
polyLat[6] = 9.899107;
polyLat[7] = 9.993088;
polyLat[8] = 10.081425;
polyLat[9] = 9.992266;
polyLat[10] = 10.194027;//First point repeated to close polygon
var polySides = (polyLat.length)-1;//number of points in polygon
//vertical Longitude coordinates of polygon
var polyLng = new Array();
polyLng[0] = 76.201205;
polyLng[1] = 76.375022;
polyLng[2] = 76.775730;
polyLng[3] = 76.778940;
polyLng[4] = 76.584336;
polyLng[5] = 76.411473;
polyLng[6] = 76.368070;
polyLng[7] = 76.397007;
polyLng[8] = 76.317492;
polyLng[9] = 76.267905;
polyLng[10] = 76.201205;//First point repeated to close polygon
//Coordinates for bounding box
var maxLat = Math.max.apply(null,polyLat);
var minLat = Math.min.apply(null,polyLat);
var maxLng = Math.max.apply(null,polyLng);
var minLng = Math.min.apply(null,polyLng);
$.post('outboundupd.jsp',
{
mx_lat:maxLat,
mn_lat:minLat,
mx_lng:maxLng,
mn_lng:minLng,
ply_sds:polySides
},
function(response,status,xhr)
{
// alert(response.trim());
plotdata(response);
});
function plotdata(response)
{
var x;
var y;
var mob;
var jsonArray=JSON.parse(response.trim());
var jalen= jsonArray.length;
for(i=0;i<jalen;i++)
{
var obj=jsonArray[i];
pcode= obj.Pcode;
nplate= obj.N_plate;
driver= obj.Driver;
mob= obj.MobileNu;
x= obj.Latitude;
y= obj.Longitude;
time= obj.Time;
}
var j = polySides-1 ;
oddNodes = 0;
for (i=0; i<polySides; i++) {
if (polyLng[i]<y && polyLng[j]>=y || polyLng[j]<y && polyLng[i]>=y) {
if (polyLat[i]+(y-polyLng[i])/(polyLng[j]-polyLng[i])*(polyLat[j]-polyLat[i])<x) {
oddNodes=!oddNodes;
}
}
j=i; }
if(oddNodes!=true)
{
// alert("ob mobile:"+mob);
$.post('obsouth.jsp',
{
pcd:pcode,
npt:nplate,
drv:driver,
mobl:mob,
lat:x,
lon:y,
tm:time
},
function(response,status,xhr)
{
alert(response.trim());
});
}
return oddNodes;
}
});
</script>
I need the above code to be executed periodically after server start, so i had used context listner and implemented runnable in a new java class, below is my java class:-
package com.my.classes;
public class obrecord implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
}
}
Now, i need to execute the above javascript code in the below java class to run it periodically on server start. is there any method to do it? or is there any alternative efficient method to get the job done? Any piece of code is highly appreciated and thanks in advance.
Create a function which is going to be called periodically.
and use this function of javascript.
var intervalID = setInterval(function_name(), 5000);
There is no need to write java code.
I think this question can help :
Is there any way to call a function periodically in JavaScript?
I am new to Gwt,i m implementing a webclipper project so my task to send some parameters from javascript file to Gwt so that i will be able to make the connection with my couchdb database but i am getting a problem in passing parameters like title, url ,and summary from webpage to Gwt n then couchdb.The following code is my javascript code:-
function onPageInfo(o) {
document.getElementById('title').value = o.title;
document.getElementById('url').value = o.url;
document.getElementById('summary').innerText = o.summary;
}
// Global reference to the status display SPAN
var statusDisplay = null;
// POST the data to the server using XMLHttpRequest
function addBookmark() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = "http://127.0.0.1:8888/practice.html? gwt.codesvr=127.0.0.1:9997&gwt.codesvr=127.0.0.1:9997/?title=1&url=2&summary=3";
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed
var title = encodeURIComponent(document.getElementById('title').value);
var url = encodeURIComponent(document.getElementById('url').value);
var summary = encodeURIComponent(document.getElementById('summary').value);
var tags = encodeURIComponent(document.getElementById('tags').value);
var params = 'title=' + title +
'&url=' + url +
'&summary=' + summary +
'&tags=' + tags;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/json');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
window.setTimeout(window.close, 1000);
} else {// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
}
// When the popup HTML has loaded
window.addEventListener('load', function(evt) {
// Handle the bookmark form submit event with our addBookmark function
document.getElementById('addbookmark').addEventListener('submit', addBookmark);
// Cache a reference to the status display SPAN
statusDisplay = document.getElementById('status-display');
// Call the getPageInfo function in the background page, injecting content_script.js
// into the current HTML page and passing in our onPageInfo function as the callback
chrome.extension.getBackgroundPage().getPageInfo(onPageInfo);
});
Thanks.....
You can call a function defined in a java file (of GWT client module) by exporting that function. Let's assume there is a class A.java which is also your entry point class. This class contains someMethod() which you need to call from javascript passing some parameters. The content of your class A would be something like
public class A implements EntryPoint {
public static functionExported = false;
public void onModuleLoad() {
ExportToBeCalledFromJs();
// other code goes here
}
public static native void ExportToBeCalledFromJs() /*-{
$wnd.toBeCalledFromJs = $entry(function(s1, s2) {
return #com.practice.gwt.client.A::someFunction();
});
#com.practice.gwt.client.A:functionExported = true;
}-*/;
}
Above code exports the function and makes it available to javascript. You can simply call toBeCalledFromJs(param1, param2) fromyour js where param1 would substitute s1 and param2 would substitute s2. If you wish to add more parameters you can modify $entry(function(s1, s2) in the code above.
I'm wondering if it is possible to call a function from a java json object?
Example
java:
JSONObject json = new JSONObject();
json.put("fnRowCallback", "test()");
jquery:
$ (function () {
"use strict";
function test() {
alert('test');
}
}(jQuery));
Ultimate accomplishment needed.
JSONObject json = new JSONObject();
json.put("fnRowCallback", function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if (aData["rush"] == "Rush" ) {
$(nRow).addClass("gradeX");
}
});
You can accomplish this if you instead have your Java return javascript.
<script src="myjavapage.jsp"></script>
have your Java return
$(function(){
alert('test');
});
however I can't think of a good reason to code it this way rather than instead having a js file that gets the content on demand using ajax and not including code in your json. It seems pretty pointless.
I ended up answering my own question. The solution is to use a JSONLiteral like so,
Java
public JSONObject getOptions() {
JSONObject json = new JSONObject();
json.put("fnRowCallback", new JSONLiteral(String.format("fnRowCallback()")));
return json;
}
JS.
function fnRowCallback(){
var fnRowCallback = function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
if (aData["rush"] == "Rush" ) {
nRow.className = nRow.className + " gradeX";
}
};
return fnRowCallback;
}
Thanks Everyone.
See Function.prototype.call or Function.prototype.apply
var obj = {
foo: function() {
console.log('foo called');
}
};
var json = {method: "foo"};
obj[json.method].call(this);
How do we call javascript from Android? I have this javascript library which I would like to use, I want to call the javascript function and pass the result value to the android java code. Haven't found the answer from now. i managed to call android code from javascript, but I want the other way around.
There is a hack:
Bind some Java object so that it can be called from Javascript with WebView:
addJavascriptInterface(javaObjectCallback, "JavaCallback")
Force execute javascript within an existing page by
WebView.loadUrl("javascript: var result = window.YourJSLibrary.callSomeFunction();
window.JavaCallback.returnResult(result)");
(in this case your java class JavaObjectCallback should have a method returnResult(..))
Note: this is a security risk - any JS code in this web page could access/call your binded Java object. Best to pass some one-time cookies to loadUrl() and pass them back your Java object to check that it's your code making the call.
You can use Rhino library to execute JavaScript without WebView.
Download Rhino first, unzip it, put the js.jar file under libs folder. It is very small, so you don't need to worry your apk file will be ridiculously large because of this one external jar.
Here is some simple code to execute JavaScript code.
Object[] params = new Object[] { "javaScriptParam" };
// Every Rhino VM begins with the enter()
// This Context is not Android's Context
Context rhino = Context.enter();
// Turn off optimization to make Rhino Android compatible
rhino.setOptimizationLevel(-1);
try {
Scriptable scope = rhino.initStandardObjects();
// Note the forth argument is 1, which means the JavaScript source has
// been compressed to only one line using something like YUI
rhino.evaluateString(scope, javaScriptCode, "JavaScript", 1, null);
// Get the functionName defined in JavaScriptCode
Object obj = scope.get(functionNameInJavaScriptCode, scope);
if (obj instanceof Function) {
Function jsFunction = (Function) obj;
// Call the function with params
Object jsResult = jsFunction.call(rhino, scope, scope, params);
// Parse the jsResult object to a String
String result = Context.toString(jsResult);
}
} finally {
Context.exit();
}
You can see more details at my post.
In order to match the method calls of the iOS WebviewJavascriptBridge ( https://github.com/marcuswestin/WebViewJavascriptBridge ), I made some proxy for the calls of register_handle and call_handle. Please note I am not a Javascript-guru therefore there is probably a better solution.
javascriptBridge = (function() {
var handlers = {};
return {
init: function () {
},
getHandlers : function() {
return handlers;
},
callHandler : function(name, param) {
if(param !== null && param !== undefined) {
JSInterface[name](param);
} else {
JSInterface[name]();
}
},
registerHandler : function(name, method) {
if(handlers === undefined) {
handlers = {};
}
if(handlers[name] === undefined) {
handlers[name] = method;
}
}
};
}());
This way you can send from Javascript to Java calls that can have a String parameter
javascriptBridge.callHandler("login", JSON.stringify(jsonObj));
calls down to
#JavascriptInterface
public void login(String credentialsJSON)
{
Log.d(getClass().getName(), "Login: " + credentialsJSON);
new Thread(new Runnable() {
public void run() {
Gson gson = new Gson();
LoginObject credentials = gson.fromJson(credentialsJSON, LoginObject.class);
SingletonBus.INSTANCE.getBus().post(new Events.Login.LoginEvent(credentials));
}
}).start();
}
and you can call back to Javascript with
javascriptBridge.registerHandler('successfullAuthentication', function () {
alert('hello');
})
and
private Handler webViewHandler = new Handler(Looper.myLooper());
webViewHandler.post(
new Runnable()
{
public void run()
{
webView.loadUrl("javascript: javascriptBridge.getHandlers().successfullAuthentication();"
}
}
);
If you need to pass a parameter, serialize to JSON string then call StringEscapeUtils.escapeEcmaScript(json), otherwise you get unexpected identifier: source (1) error.
A bit tacky and hacky, but it works. You just have to remove the following.
connectWebViewJavascriptBridge(function(bridge) {
}
EDIT:
in order to change the global variable to an actual property, I changed the above code to the following:
(function(root) {
root.bridge = (function() {
var handlers = {};
return {
init: function () {
},
getHandlers : function() {
return handlers;
},
callHandler : function(name, param) {
if(param !== null && param !== undefined) {
Android[name](param);
} else {
Android[name]();
}
},
registerHandler : function(name, method) {
if(handlers === undefined) {
handlers = {};
}
if(handlers[name] === undefined) {
handlers[name] = method;
}
}
};
}());
})(this);
I got the idea from Javascript global module or global variable .
For a full implementation of JavaScript that doesn't require using a slow WebView, please see AndroidJSCore, which is a full port of Webkit's JavaScriptCore for Android.
UPDATE 2018: AndroidJSCore is deprecated. However, its successor, LiquidCore has all of the same functionality and more.
Calling functions from Android is very simple:
JSContext context = new JSContext();
String script =
"function factorial(x) { var f = 1; for(; x > 1; x--) f *= x; return f; }\n" +
"var fact_a = factorial(a);\n";
context.evaluateScript("var a = 10;");
context.evaluateScript(script);
JSValue fact_a = context.property("fact_a");
System.out.println(df.format(fact_a.toNumber())); // 3628800.0