I'm trying to call a JavaScript function from Java code. My code is as follows:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
String script = baseUrl + "UIConfigurator/includes/js/DataCaptureFramework.js";
try {
LOGGER.info("evaluating engine");
LOGGER.info(script);
URL url1 = new URL(script);
LOGGER.info("url1 "+url1.getPath()+url1);
BufferedReader in = new BufferedReader(
new InputStreamReader(url1.openStream()));
String inputLine = null;
StringBuffer buffer = new StringBuffer();
while ((inputLine = in.readLine()) != null)
buffer.append(inputLine);
LOGGER.info(buffer.toString());
engine.eval(buffer.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
LOGGER.error(e.toString());
LOGGER.error("Throwing error in the catch part");
}
Invocable inv = (Invocable) engine;
try {
LOGGER.info("invoking function");
inv.invokeFunction("displayDataCapturePopUp("+user.getOrgId()+","+user.getId()+","+session.getLoginType()+");");
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ScriptException e) {
// TODO Auto-generated catch block
LOGGER.error("throwing error in catch block of invoking engine and function");
}
When I run this code it gives me the following error:
11:53:50,847 ERROR [Login] javax.script.ScriptException:
sun.org.mozilla.javascript.internal.EcmaError: ReferenceError:
"jQuery" is not defined. (#1) in at
line number 1 11:53:50,847 ERROR [Login] Throwing error in the catch
part 11:53:50,848 INFO [Login] invoking function 11:53:50,848 ERROR
[STDERR] java.lang.NoSuchMethodException: no such method:
displayDataCapturePopUp(301,1373864,0);
I tried a lot of things but still cannot get rid of this. Please tell me what I'm doing wrong. I'm trying to call the below function from JavaScript.
function displayDataCapturePopUp(orgId,userId,loginTypeId){ jQuery(" <link/>", {rel: "stylesheet",type: "text/css",href:
"/UIConfigurator/includes/css/librarycss/jquery-ui.min.css"}).appendTo("head"); jQuery("<link/>", {rel: "stylesheet",type: "text/css",href:
"/UIConfigurator/includes/css/DataCaptureFramework.css"}).appendTo("head"); jQuery("<link/>", {rel: "stylesheet",type: "text/css",href:
"/UIConfigurator/includes/css/librarycss/tooltipster.css"}).appendTo("head"); jQuery("<link/>", {rel: "stylesheet",type: "text/css",href:
"/UIConfigurator/includes/css/librarycss/jquery.alerts.css"}).appendTo("head");
jQuery.getScript('/UIConfigurator/includes/js/UiAjaxInteraction.js',function() {
jQuery.getScript('/iONjsLib/js/jquery-ui-1.10.4.min.js',function() {
jQuery.getScript('/iONjsLib/js/jquery.tooltipster.min.js',function() {
jQuery.getScript('/UIConfigurator/includes/js/libraryjs/jquery.alerts.js',function() {
jQuery.getScript('/iONjsLib/js/jquery.blockUI.js',function() {
getDataCapturePopUpDetails(orgId,userId,loginTypeId); }
);
}
);
}
);
}
);
}
);
}
ScriptEngine runs JavaScript in an entirely separate environment, with no access to your browser. It looks like you're trying to use it to show some kind of popup in your browser; this will not work. If you need to control your browser remotely, you need to use a different API, not ScriptEngine.
Related
I have a springboot app that calls a .jsx script. It is a simple script, just read a JSON file and print some values on console.
My problem is when I try to get the output and log on my springboot app.
When I run the script using ExtendToolkit Script, I get the follow info on console:
Id: 6989996500
Result: undefined
But, when I run through Springboot, the output is:
Exit status: 0
Output: [TypeQuest] Timestamp=2023-02-01T05:00:19.434 ThreadId=6304 Type=TQ_WARN Component=TQFontManager Description="Not using user-specific cache directory; using: C:\Users\lnrei\AppData\Roaming\Adobe\typequest.2"
Here is my spring code:
`
try {
String[] command = {"C:\\Program Files\\Adobe\\Adobe Photoshop 2022\\Photoshop.exe",
"-r",
"C:\\Users\\lnrei\\OneDrive\\Documentos\\Projeto\\Photoshop Scripts\\scriptPSthumbnail.jsx"};
//Process process = new ProcessBuilder(command).start();
Process process = Runtime.getRuntime().exec(command);
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while((line = reader.readLine()) != null)
output.append(line + "\n");
int exit = process.waitFor();
System.out.println("Exit status: " + exit);
System.out.println("Output: " + output);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}`
As you can see, I trying to use process.getInputStream() to catch the output and sendo to a string.
Here is my .jsx file:
`
#include "json2.js";
var contentPath = "C:/Users/lnrei/OneDrive/Documentos/Projeto/content/content.json";
var contentFile = new File(contentPath);
if(contentFile.exists) {
contentFile.open("r");
var jsonStr = contentFile.read ();
contentFile.close ();
var content = JSON.parse(jsonStr);
$.writeln ("Id: " + content.matchId)
} else {
$.writeln ("Error handling the file!");
}
$.writeln();
photoshop.quit();`
Am working on protractor framework and I need to upload files to the application using a script.I know how to do it in java but no idea in javascript. Can someone please help me on this:
Java code :
public static void fileUpload(String script, String filePath) {
try {
Process proc = Runtime.getRuntime().exec("script " + script + " " + filePath);
BufferedReader read = new BufferedReader(new InputStreamReader(proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}catch (IOException e) {
System.out.println(e.getMessage());
}
}
Thanks !
Not sure what you meant by script here. Using sendkeys with upload input element should work in protractor.
like :
var path = require('path');
var fileToUpload = '../test-resources/filetoupload'; //(the example relative path of the file )
var absolutePath = path.resolve(__dirname, fileToUpload);
element(by.css('input[type="file"]')).sendKeys(absolutePath);
uploadButton().click();
I am using ScriptEngineManager in my grails application to execute javascript code.
When I execute this javascript:
var x = new java.util.ArrayList([1, 2, 3])
log(x[55])
With this code:
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript")
return engine.eval(javascript)
} catch (ScriptException jsEx) {
// Exception is added in outer function to the log
throw new JavascriptException(jsEx.getMessage(), jsEx)
} catch (Exception e) {
throw new JavascriptException("UNEXPECTED Exception in invokeJavaScript " + e.getMessage(), e)
}
I get a java.lang.IndexOutOufBoundsExceptionin the Excpetion e. This is okay, but I want to know which line in the javascript the error occured.
Is there a possibility to get the last successful line from javascript code?
I found a workaround for my problem. I parse the stacktrace of the exception so I get the line number:
//this method gives me the stacktrace as string
String trace = helperService.stacktraceToString(e)
String line = ""
trace.eachLine {
if (it.contains("<eval>")) {
line = " at line " + it.substring(it.lastIndexOf("<eval>:"), it.length() -1).replace("<eval>:", "")
}
}
I have to call a javascript function named function startPolling() and created into hill.js file (/Demo MM/src/main/webapp/static/assets/js/hill.js) from java code. How can i do?Thanks
I'm using this code but receive exception
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
if (!(engine instanceof Invocable)) {
System.out.println("Invoking methods is not supported.");
return "500";
}
Invocable inv = (Invocable) engine;
String scriptPath = "/Demo MM/src/main/webapp/static/assets/js/hill.js";
try {
engine.eval("load('" + scriptPath + "')");
} catch (ScriptException e) {
return "500";
}
Make sure you are in the correct working directory to begin with. I get your code working.
To output working directory:
System.out.println("Working Directory = " +
System.getProperty("user.dir"));
I have been trying to transfer audio files between my android app and my node-webkit app but I'm new to the world of socket.io/nodejs/delivery.js.
Here is my code:
android-code ERROR-LINE: os.write(mybytearray, 0, mybytearray.length);
protected Void doInBackground(Void... arg0) {
Socket sock;
try {
// sock = new Socket("MY_PCs_IP", 1149);
sock = new Socket("192.168.0.10", 5001);
System.out.println("Connecting...");
// sendfile
File myFile = new File(this.currentSong.getPath());
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
System.out.println("Sended..");
// RESPONSE FROM THE SERVER
BufferedReader in = new BufferedReader(
new InputStreamReader(sock.getInputStream()));
in.ready();
String userInput = in.readLine();
System.out.println("Response from server..." + userInput);
sock.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
node-webkit-code
var io = require('socket.io').listen(5001),
dl = require('delivery'), //delivery.server
fs = require('fs');
io.sockets.on('connection', function(socket){
delivery = dl.listen(socket);
delivery.on('receive.success',function(file){
fs.writeFile("music/"+file.name,file.buffer, function(err){
if(err){
console.log('File could not be saved.');
}else{
console.log('File saved.');
addSong("music/"+file.name);
};
});
});
});
Note: My server side works well it's already tested by a js client
This is the error I am getting:
Android side Error:
08-28 14:56:36.180: W/System.err(30510): java.net.SocketException: sendto failed: EPIPE (Broken pipe)
08-28 14:56:36.180: W/System.err(30510): at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:499)
08-28 14:56:36.180: W/System.err(30510): at libcore.io.IoBridge.sendto(IoBridge.java:468)
08-28 14:56:36.180: W/System.err(30510): at java.net.PlainSocketImpl.write(PlainSocketImpl.java:507)
So maybe I'm wrong trying to do a bad connection because of protocols.. between a socket and socket.io..?
if any one can help my out I will be pleased. I already looked around but as I said I'm new to this world and I get hazy
basically my question is: What's wrong? and How I accomplish my objective?
Thanks for your time
I am using com.koushikdutta.async.http.socketio.SocketIOClient
there is some problems with this library and socket.io but it it's solved by using this dependency on node-webkit
"socket.io": "~0.9",
also need to read file->base64 codification-> then emit the string on the server side must do this:
socket.on('finishFileTransfer',function(){
fs.writeFile("music/"+fileName,new Buffer(file,'base64'), function(err){
if(err){
console.log('File could not be saved.');
}else{
console.log('File saved.');
addSong("musica/"+fileName);
}
file = "";
fileName = null;
});
});