How to run my javascript functions in Java class implemented runnable? - java

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?

Related

Android/Java: Waiting until closure has completed running

I'm having trouble with some async programming within an Android application. I have some code in the ClientLocation class that gets the user's lat/lon, but once I get them I need to pass them to a function. When stepping through the code I can see that the repository.getDeals call is run before the gotLocation closure is entered.
Here's the important bit of code:
...
this.repository = Repository.getInstance();
ClientLocation.LocationResult locationResult = new ClientLocation.LocationResult() {
#Override
public void gotLocation(Location location) {
userLatitude = Double.toString(location.getLatitude());
userLongitude = Double.toString(location.getLongitude());
}
};
ClientLocation clientLocation = new ClientLocation();
clientLocation.getLocation(getApplication().getApplicationContext(), locationResult);
// I need the latitude and longitude values at this point in order to properly call getDeals
// currently when this is called the userLat/lon values are 0.0 because gotLocation didn't run yet
deals = repository.getDeals(searchQuery, maxDistInKm, userLatitude, userLongitude);
What's a pattern where getDeals won't be called before gotLocation has completed running? New to async programming so any other tips are welcome!
Here:
boolean isFinished = false
Thread {
this.repository = Repository.getInstance();
ClientLocation.LocationResult locationResult = new
ClientLocation.LocationResult() {
#Override
public void gotLocation(Location location) {
userLatitude = Double.toString(location.getLatitude());
userLongitude = Double.toString(location.getLongitude());
isFinished = true
}
};
while(true){
if(isFinished ) break:
}
ClientLocation clientLocation = new ClientLocation()
clientLocation.getLocation(getApplication().getApplicationContext(), locationResult);
deals = repository.getDeals(searchQuery, maxDistInKm,
userLatitude, userLongitude);
Thread.currentThread().interrupt()
}

How to get a list of Lat Longs of a certain type using Google Places API without double requesting?

This is my code
mGeoDataClient.getAutocompletePredictions("Supermarket", null, null).addOnSuccessListener {
it.forEach {
it.placeId?.let {
mGeoDataClient.getPlaceById(it).addOnSuccessListener {
val marker = it[0].latLng
val name = it[0].name.toString()
mMap.addMarker(MarkerOptions().position(marker).title(name))
}
}
}
}
For every supermarket it finds it has to request again to get the lat long as this information isn't included on the autocomplete prediction, only the place id.
Is there a better way of doing this?
You can't save the double call as far as I can tell, but since you are getting back a list you can save the n number of calls by using the getPlaceById(String... placeIds) call.
mGeoDataClient.getAutocompletePredictions("Supermarket", null, null).addOnSuccessListener {
it.map{ it.placeId}.filterNotNull().toTypedArray().let {
mGeoDataClient.getPlaceById(*it).addOnSuccessListener {
it.forEach{
val marker = it.latLng
val name = it.name.toString()
mMap.addMarker(MarkerOptions().position(marker).title(name))
}
}
}
}
You can try this. It worked fine.
mGeoDataClient?.getAutocompletePredictions("Supermarket", null, null)?.addOnSuccessListener{
it.forEach { prediction ->
val placeId = prediction.placeId
val pendingResult = Places.GeoDataApi.getPlaceById(mGoogleApiClient!!, placeId)
pendingResult.setResultCallback { placeBuffer->
val place = placeBuffer.get(0)
val marker = place.latLng
val name = place.name.toString()
mMap.addMarker(MarkerOptions().position(marker).title(name))
}
}
}
and this is how my mGoogleApiClient initializes:
private var mGoogleApiClient: GoogleApiClient? = null
mGoogleApiClient = GoogleApiClient.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build()
Hope it can help you.

WebSocket in Javascript not connecting to servlet

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

passing parameters from javascript to gwt?

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.

How to call javascript from Android?

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

Categories

Resources