Paste e.clipboardData.items always undefined - java

I'm using Chrome for my GWT app via JSNI to get the clipboardData
$doc.onpaste = function( e ) {
var pastedText = undefined;
if (e.clipboardData && e.clipboardData.getData) {
var items = e.clipboardData.items; // undefined!
}
}
Not sure why items is undefined when clipboardData and clipboardData.getData is not undefined. What could be wrong in my app?

Related

calling rest API(locally running) from nodejs failed

We created a rest API on python and it is locally running. And the 'http://127.0.0.1:5002/business' API is showing contents {"business name": "something"} if I open it on google chrome. However, when we call this API in nodejs, it always gives me the error. But if I use another API(exactly same code but different api in nodejs), it is working.
async function get_recommend_initial(){
//https://ViolaS.api.stdlib.com/InitialRecommendation#dev/
// // agent.add('providing recommendations...');
const options = {
method: 'GET'
,uri: 'http://127.0.0.1:5002/business'
// ,uri:'https://ViolaS.api.stdlib.com/InitialRecommendation#dev/'
// ,json: true
};
// return request(options).then(response => {
// console.log(response)
// return (response)
// }).catch(function (err) {
// console.log('No recommend data');
// console.log(err);
// });
return requestAPI(options).then(function(data)
{
let initial_recommendation = JSON.parse(data);
console.log(initial_recommendation);
//return initial_recommendation.information[0].name;
}).catch(function (err) {
console.log('No recommend data');
console.log(err);
});
}
1
The API that is created by python file which is running locally. You can see the API code figure by moving your mouth above 1. Thanks!!!
The python code is as follows:
app = Flask(__name__)
#Add resources to be much cleaner
api = Api(app)
features = {}
class Business(Resource):
def get(self):
return {'business name': 'something'} # Fetches first column that is Employee ID
def post(self):
some_json = request.get_json()
print(some_json)
countNumber = features.get('count',0) + 1
features['count'] = countNumber
return {'You sent': some_json,
'Count:':countNumber}, 201
def put(self):
some_json = request.get_json()
print(some_json)
#record the count number
countNumber = features.get('count',0) + 1
features['count'] = countNumber
features['ok'] = 'yes'
return {'You sent': some_json,
'Count:':countNumber,
'Ok:': features['ok']}, 201
api.add_resource(Business, '/business') # Route_1
if __name__ == '__main__':
app.run(port='5002')
The error is as following:
dialogflowFirebaseFulfillment
Error: Unknown response type: "undefined" at WebhookClient.addResponse_ (/srv/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:277:13) at WebhookClient.add (/srv/node_modules/dialogflow-fulfillment/src/dialogflow-fulfillment.js:245:12) at Sys_Recommend (/srv/index.js:31:11) at <anonymous>
And the log is:
No recommend data

Execute script in web browser (python - selenium)

within a web page is a script that allows you to see a video and other.
using python and selenium can not be run the script after the mouse clicks. Of the currently am using this code:
videoGemPath = ".//*[#id='brandconnect']/a/img"
scriptPath = ".//*[#id='content']/script"
elementScript = "/html/body/div[2]/div[1]"
location = driver.find_element_by_xpath(scriptPath)
ActionChains(driver).move_to_element(location).click().perform()
but it returns this error
=========================================================================
Traceback (most recent call last):
File "C:\Users\xxxxxx\Desktop\Proggetti VB\Per Web\PythonApplication4\PythonApplication4\PythonApplication4.py", line 66, in test_Login
ActionChains(driver).move_to_element(location).click().perform()
File "C:\Python27\lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\common\action_chains.py", line 72, in perform
action()
File "C:\Python27\lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\common\action_chains.py", line 217, in
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
File "C:\Python27\lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\remote\webdriver.py", line 201, in execute
self.error_handler.check_response(response)
File "C:\Python27\lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\remote\errorhandler.py", line 181, in check_response
raise exception_class(message, screen, stacktrace)
MoveTargetOutOfBoundsException: Message: Offset within element cannot be scrolled into view: (352.5, 241.5): [object HTMLScriptElement]
Stacktrace:
at FirefoxDriver.prototype.mouseMoveTo (file:///c:/users/xxxxxx/appdata/local/temp/tmpgnvb0k/extensions/fxdriver#googlecode.com/components/driver-component.js:10961)
at DelayedCommand.prototype.executeInternal_/h (file:///c:/users/xxxxxx/appdata/local/temp/tmpgnvb0k/extensions/fxdriver#googlecode.com/components/command-processor.js:12534)
at DelayedCommand.prototype.executeInternal_ (file:///c:/users/xxxxxx/appdata/local/temp/tmpgnvb0k/extensions/fxdriver#googlecode.com/components/command-processor.js:12539)
at DelayedCommand.prototype.execute/< (file:///c:/users/xxxxxxx/appdata/local/temp/tmpgnvb0k/extensions/fxdriver#googlecode.com/components/command-processor.js:12481)
=========================================================================
the script code is this:
// create button
document.write('<div id="brandconnect"><img src="img/bconnect_area.png" class="tooltip" rel="Guarda video e ricevi Gemme gratis!" alt="" /></div>');
// ini local storage to save last button state if this html5 feature is available
var storage = false;
try {
if( window && window.localStorage ) {
storage = window.localStorage;
if( typeof(storage.bcVisible) === 'string' ) {
if( storage.bcVisible == 'true' ) {
showBC();
}
else {
hideBC();
}
}
}
}
catch( ignore ) {
// local storage might require user approval. in this case we don't use it
}
// handle button visibility
function handleBC(obj) {
if( typeof(obj) != 'object' || obj.length < 1 ) {
// no videos available
hideBC();
}
else {
// videos are available
showBC();
}
}
// show brandconnect button
function showBC() {
clink = document.getElementById('brandconnect');
if( clink ) {
clink.style.display = 'block';
}
if( storage ) {
storage.bcVisible = 'true';
}
}
// hide brandconnect button
function hideBC() {
document.getElementById('brandconnect').style.display = 'none';
if( storage ) {
storage.bcVisible = 'false';
}
}
function hoverBC() {
document.getElementById('brandconnect').style.backgroundPosition = '-89px 0';
}
function unhoverBC() {
document.getElementById('brandconnect').style.backgroundPosition = '0 0';
}
// definitions by JSON
var ssa_json = {
'applicationUserId': '512000516',
'applicationKey': '2ae25b1d',
'currencyName': 'Gemme',
'onCampaignsReady': handleBC,
'onCampaignsDone': hideBC,
'onCampaignCompleted': handleBC,
'onCampaignClose': handleBC
};
// embed supersonic script
(function(d,t){
var g = d.createElement(t), s = d.getElementsByTagName(t)[0]; g.async = true;
g.src = ('https:' != location.protocol ? 'http://jsd.supersonicads.com' :
'https://supersonicads.cotssl.net') + '/inlineDelivery/delivery.min.gz.js';
s.parentNode.insertBefore(g,s);
}(document,'script'));
//]]>
How can I fix it?

How to run javascript function periodically when the Apache tomcat server is starts instead of java class using ScheduledExecutorService?

I need to run my javascript function periodically on server starts. i dont know how to write the equivalent Java code as my javaScript function contains multiple ajax call and mathematical equations.
below is my javascript code which i need to run periodically on server start.
<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>
My question:-
Is there any technique to call a javascript function from a java class extended with runnables or directly implement the exact javascript in java class?
If answer for 1 is no, can you please guide me to convert my entire javascript to Java code?
Any piece of code is highly appreciated and thanks in advance.
Use node.js and execute your script using Runtime.exec(). you would run node on this or you can go for Rhino scripting engine to envoke methods in .js file from within a java class. Hope that helped.

Object doesn't support this method or property error

Hi I created a jni jar and i call the jar using applet in java script. I use the following applet tag to create a object to call jar functions through java script. when i call the function i got the following error Object doesn't support this method or property.
Here is my code.
document.write('<applet code="BiomAPI.Legend.class" width="0" height="0" archive="BiomAPI.jar" id="Obj"></applet>');
function GetTemplateAccurate (sUserID,iFingerID)
{
document.getElementsByName("Enroll")[0].value = "";
document.getElementsByName("Image")[0].value = "";
var lsFeature = null;
var lsImage = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SaveImage(1);
Obj.SessionID("abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde");
Obj.GetFeatureAccrual(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null && lsImage != null )
{
document.getElementsByName("Enroll")[0].value = lsFeature;
document.getElementsByName("Image")[0].value = lsImage;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
function GetTemplate(sUserID,iFingerID)
{
document.getElementsByName("Verify")[0].value = "";
var lsFeature = null;
Obj.EnableLog(0);
Obj.LocalFilePath("C:\\IMAGE\\");
Obj.EnableEncryption(0);
Obj.SessionID("abcde");
Obj.SaveImage(1);
Obj.GetFeature(sUserID,iFingerID);
lsFeature = Obj.Feature();
lsImage = Obj.StringImage();
if (lsFeature != null)
{
document.getElementsByName("Verify")[0].value = lsFeature;
alert("Scanner Working Properly");
}
else
{
alert("Fingerprint not captured");
}
}
as exception itself is describing:
Object doesn't support this method or property error
the property or method you are trying to access with an object is not supported by that object. Please debug or see on error console the object throwing exception and find whether it support that property you are trying to access.

DJ Native Swing javascript command problems

Using DJ Native Swing it is possible to show a web page within a java application. When you do this it is also possible to communicate from the browser to the java runtime environment using the "command" protocol. The documentation has a code snippet which demonstrates it's usage:
function sendCommand( command ){
var s = 'command://' + encodeURIComponent( command );
for( var i = 1; i < arguments.length; s+= '&' + encodeURIComponent( arguments[i++] ) );
window.location = s;
}
As it looks here it seems to be a regular GET request to an url using the command protocol instead of http. Although when I create and image, script tag or just and ajax get request there is no response and the breakpoint in the java runtime isn't triggered.
I don't want to set the window.location because I don't want to navigate away from the page I am currently at. Using the link to navigate to a command url does work though but it also navigates away from the current page. The page uses OpenLayers and dojo. (I have also tried dojo.io.script)
After some work I have found a neat way to communicate with the java runtime which doesn't trigger a refresh of the page every time there is communication. It is inspired on the way JSONP works to get around the cross domain restriction in most browsers these days. Because an iFrame will also trigger a command:// url it possible to do a JSONP like action using this technique. The code on the client side (browser):
dojo.provide( "nmpo.io.java" );
dojo.require( "dojo.io.script" );
nmpo.io.java = dojo.delegate( dojo.io.script, {
attach: function(/*String*/id, /*String*/url, /*Document?*/frameDocument){
// summary:
// creates a new tag pointing to the specified URL and
// adds it to the document.
// description:
// Attaches the script element to the DOM. Use this method if you
// just want to attach a script to the DOM and do not care when or
// if it loads.
var frame = dojo.create( "iframe", {
id: id,
frameborder: 0,
framespacing: 0
}, dojo.body( ) );
dojo.style( frame, { display: "none" } );
dojo.attr( frame, { src: url } );
return frame;
},
_makeScriptDeferred: function(/*Object*/args){
//summary:
// sets up a Deferred object for an IO request.
var dfd = dojo._ioSetArgs(args, this._deferredCancel, this._deferredOk, this._deferredError);
var ioArgs = dfd.ioArgs;
ioArgs.id = dojo._scopeName + "IoScript" + (this._counter++);
ioArgs.canDelete = false;
//Special setup for jsonp case
ioArgs.jsonp = args.callbackParamName || args.jsonp;
if(ioArgs.jsonp){
//Add the jsonp parameter.
ioArgs.query = ioArgs.query || "";
if(ioArgs.query.length > 0){
ioArgs.query += "&";
}
ioArgs.query += ioArgs.jsonp
+ "="
+ (args.frameDoc ? "parent." : "")
+ "nmpo.io.java.jsonp_" + ioArgs.id + "._jsonpCallback";
ioArgs.frameDoc = args.frameDoc;
//Setup the Deferred to have the jsonp callback.
ioArgs.canDelete = true;
dfd._jsonpCallback = this._jsonpCallback;
this["jsonp_" + ioArgs.id] = dfd;
}
return dfd; // dojo.Deferred
}
});
When a request is sent to the java runtime a callback argument will be supplied and a webBrowser.executeJavascript( callbackName + "(" + json + ");" ); action can be executed to trigger the callback in the browser.
Usage example client:
dojo.require( "nmpo.io.java" );
nmpo.io.java.get({
// For some reason the first paramater (the one after the '?') is never in the
// paramater array in the java runtime. As a work around we stick in a dummy.
url: "command://sum?_",
callbackParamName: "callback",
content: {
numbers: [ 1, 2, 3, 4, 5 ].join( "," )
},
load: function( result ){
console.log( "A result was returned, the sum was [ " + result.result + " ]" );
}
});
Usage example java:
webBrowser.addWebBrowserListener(new WebBrowserAdapter() {
#Override
public void commandReceived(WebBrowserCommandEvent e) {
// Check if you have the right command here, left out for the example
// Parse the paramaters into a Hashtable or something, also left out for the example
int sum = 0;
for( String number : arguments.get( "numbers" ).split( "," ) ){
sum += Integer.parseInt( number );
}
// Execute the javascript callback like would happen with a regular JSONP call.
webBrowser.executeJavascript( arguments.get( "callback" ) + "({ result: " + sum + " });" );
}
});
Also with IE in the frame I can highly recommend using firebug lite, the dev tools for IE are not available.

Categories